babylon.max.js 4.3 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411854128541385414854158541685417854188541985420854218542285423854248542585426854278542885429854308543185432854338543485435854368543785438854398544085441854428544385444854458544685447854488544985450854518545285453854548545585456854578545885459854608546185462854638546485465854668546785468854698547085471854728547385474854758547685477854788547985480854818548285483854848548585486854878548885489854908549185492854938549485495854968549785498854998550085501855028550385504855058550685507855088550985510855118551285513855148551585516855178551885519855208552185522855238552485525855268552785528855298553085531855328553385534855358553685537855388553985540855418554285543855448554585546855478554885549855508555185552855538555485555855568555785558855598556085561855628556385564855658556685567855688556985570855718557285573855748557585576855778557885579855808558185582855838558485585855868558785588855898559085591855928559385594855958559685597855988559985600856018560285603856048560585606856078560885609856108561185612856138561485615856168561785618856198562085621856228562385624856258562685627856288562985630856318563285633856348563585636856378563885639856408564185642856438564485645856468564785648856498565085651856528565385654856558565685657856588565985660856618566285663856648566585666856678566885669856708567185672856738567485675856768567785678856798568085681856828568385684856858568685687856888568985690856918569285693856948569585696856978569885699857008570185702857038570485705857068570785708857098571085711857128571385714857158571685717857188571985720857218572285723857248572585726857278572885729857308573185732857338573485735857368573785738857398574085741857428574385744857458574685747857488574985750857518575285753857548575585756857578575885759857608576185762857638576485765857668576785768857698577085771857728577385774857758577685777857788577985780857818578285783857848578585786857878578885789857908579185792857938579485795857968579785798857998580085801858028580385804858058580685807858088580985810858118581285813858148581585816858178581885819858208582185822858238582485825858268582785828858298583085831858328583385834858358583685837858388583985840858418584285843858448584585846858478584885849858508585185852858538585485855858568585785858858598586085861858628586385864858658586685867858688586985870858718587285873858748587585876858778587885879858808588185882858838588485885858868588785888858898589085891858928589385894858958589685897858988589985900859018590285903859048590585906859078590885909859108591185912859138591485915859168591785918859198592085921859228592385924859258592685927859288592985930859318593285933859348593585936859378593885939859408594185942859438594485945859468594785948859498595085951859528595385954859558595685957859588595985960859618596285963859648596585966859678596885969859708597185972859738597485975859768597785978859798598085981859828598385984859858598685987859888598985990859918599285993859948599585996859978599885999860008600186002860038600486005860068600786008860098601086011860128601386014860158601686017860188601986020860218602286023860248602586026860278602886029860308603186032860338603486035860368603786038860398604086041860428604386044860458604686047860488604986050860518605286053860548605586056860578605886059860608606186062860638606486065860668606786068860698607086071860728607386074860758607686077860788607986080860818608286083860848608586086860878608886089860908609186092860938609486095860968609786098860998610086101861028610386104861058610686107861088610986110861118611286113861148611586116861178611886119861208612186122861238612486125861268612786128861298613086131861328613386134861358613686137861388613986140861418614286143861448614586146861478614886149861508615186152861538615486155861568615786158861598616086161861628616386164861658616686167861688616986170861718617286173861748617586176861778617886179861808618186182861838618486185861868618786188861898619086191861928619386194861958619686197861988619986200862018620286203862048620586206862078620886209862108621186212862138621486215862168621786218862198622086221862228622386224862258622686227862288622986230862318623286233862348623586236862378623886239862408624186242862438624486245862468624786248862498625086251862528625386254862558625686257862588625986260862618626286263862648626586266862678626886269862708627186272862738627486275862768627786278862798628086281862828628386284862858628686287862888628986290862918629286293862948629586296862978629886299863008630186302863038630486305863068630786308863098631086311863128631386314863158631686317863188631986320863218632286323863248632586326863278632886329863308633186332863338633486335863368633786338863398634086341863428634386344863458634686347863488634986350863518635286353863548635586356863578635886359863608636186362863638636486365863668636786368863698637086371863728637386374863758637686377863788637986380863818638286383863848638586386863878638886389863908639186392863938639486395863968639786398863998640086401864028640386404864058640686407864088640986410864118641286413864148641586416864178641886419864208642186422864238642486425864268642786428864298643086431864328643386434864358643686437864388643986440864418644286443864448644586446864478644886449864508645186452864538645486455864568645786458864598646086461864628646386464864658646686467864688646986470864718647286473864748647586476864778647886479864808648186482864838648486485864868648786488864898649086491864928649386494864958649686497864988649986500865018650286503865048650586506865078650886509865108651186512865138651486515865168651786518865198652086521865228652386524865258652686527865288652986530865318653286533865348653586536865378653886539865408654186542865438654486545865468654786548865498655086551865528655386554865558655686557865588655986560865618656286563865648656586566865678656886569865708657186572865738657486575865768657786578865798658086581865828658386584865858658686587865888658986590865918659286593865948659586596865978659886599866008660186602866038660486605866068660786608866098661086611866128661386614866158661686617866188661986620866218662286623866248662586626866278662886629866308663186632866338663486635866368663786638866398664086641866428664386644866458664686647866488664986650866518665286653866548665586656866578665886659866608666186662866638666486665866668666786668866698667086671866728667386674866758667686677866788667986680866818668286683866848668586686866878668886689866908669186692866938669486695866968669786698866998670086701867028670386704867058670686707867088670986710867118671286713867148671586716867178671886719867208672186722867238672486725867268672786728867298673086731867328673386734867358673686737867388673986740867418674286743867448674586746867478674886749867508675186752867538675486755867568675786758867598676086761867628676386764867658676686767867688676986770867718677286773867748677586776867778677886779867808678186782867838678486785867868678786788867898679086791867928679386794867958679686797867988679986800868018680286803868048680586806868078680886809868108681186812868138681486815868168681786818868198682086821868228682386824868258682686827868288682986830868318683286833868348683586836868378683886839868408684186842868438684486845868468684786848868498685086851868528685386854868558685686857868588685986860868618686286863868648686586866868678686886869868708687186872868738687486875868768687786878868798688086881868828688386884868858688686887868888688986890868918689286893868948689586896868978689886899869008690186902869038690486905869068690786908869098691086911869128691386914869158691686917869188691986920869218692286923869248692586926869278692886929869308693186932869338693486935869368693786938869398694086941869428694386944869458694686947869488694986950869518695286953869548695586956869578695886959869608696186962869638696486965869668696786968869698697086971869728697386974869758697686977869788697986980869818698286983869848698586986869878698886989869908699186992869938699486995869968699786998869998700087001870028700387004870058700687007870088700987010870118701287013870148701587016870178701887019870208702187022870238702487025870268702787028870298703087031870328703387034870358703687037870388703987040870418704287043870448704587046870478704887049870508705187052870538705487055870568705787058870598706087061870628706387064870658706687067870688706987070870718707287073870748707587076870778707887079870808708187082870838708487085870868708787088870898709087091870928709387094870958709687097870988709987100871018710287103871048710587106871078710887109871108711187112871138711487115871168711787118871198712087121871228712387124871258712687127871288712987130871318713287133871348713587136871378713887139871408714187142871438714487145871468714787148871498715087151871528715387154871558715687157871588715987160871618716287163871648716587166871678716887169871708717187172871738717487175871768717787178871798718087181871828718387184871858718687187871888718987190871918719287193871948719587196871978719887199872008720187202872038720487205872068720787208872098721087211872128721387214872158721687217872188721987220872218722287223872248722587226872278722887229872308723187232872338723487235872368723787238872398724087241872428724387244872458724687247872488724987250872518725287253872548725587256872578725887259872608726187262872638726487265872668726787268872698727087271872728727387274872758727687277872788727987280872818728287283872848728587286872878728887289872908729187292872938729487295872968729787298872998730087301873028730387304873058730687307873088730987310873118731287313873148731587316873178731887319873208732187322873238732487325873268732787328873298733087331873328733387334873358733687337873388733987340873418734287343873448734587346873478734887349873508735187352873538735487355873568735787358873598736087361873628736387364873658736687367873688736987370873718737287373873748737587376873778737887379873808738187382873838738487385873868738787388873898739087391873928739387394873958739687397873988739987400874018740287403874048740587406874078740887409874108741187412874138741487415874168741787418874198742087421874228742387424874258742687427874288742987430874318743287433874348743587436874378743887439874408744187442874438744487445874468744787448874498745087451874528745387454874558745687457874588745987460874618746287463874648746587466874678746887469874708747187472874738747487475874768747787478874798748087481874828748387484874858748687487874888748987490874918749287493874948749587496874978749887499875008750187502875038750487505875068750787508875098751087511875128751387514875158751687517875188751987520875218752287523875248752587526875278752887529875308753187532875338753487535875368753787538875398754087541875428754387544875458754687547875488754987550875518755287553875548755587556875578755887559875608756187562875638756487565875668756787568875698757087571875728757387574875758757687577875788757987580875818758287583875848758587586875878758887589875908759187592875938759487595875968759787598875998760087601876028760387604876058760687607876088760987610876118761287613876148761587616876178761887619876208762187622876238762487625876268762787628876298763087631876328763387634876358763687637876388763987640876418764287643876448764587646876478764887649876508765187652876538765487655876568765787658876598766087661876628766387664876658766687667876688766987670876718767287673876748767587676876778767887679876808768187682876838768487685876868768787688876898769087691876928769387694876958769687697876988769987700877018770287703877048770587706877078770887709877108771187712877138771487715877168771787718877198772087721877228772387724877258772687727877288772987730877318773287733877348773587736877378773887739877408774187742877438774487745877468774787748877498775087751877528775387754877558775687757877588775987760877618776287763877648776587766877678776887769877708777187772877738777487775877768777787778877798778087781877828778387784877858778687787877888778987790877918779287793877948779587796877978779887799878008780187802878038780487805878068780787808878098781087811878128781387814878158781687817878188781987820878218782287823878248782587826878278782887829878308783187832878338783487835878368783787838878398784087841878428784387844878458784687847878488784987850878518785287853878548785587856878578785887859878608786187862878638786487865878668786787868878698787087871878728787387874878758787687877878788787987880878818788287883878848788587886878878788887889878908789187892878938789487895878968789787898878998790087901879028790387904879058790687907879088790987910879118791287913879148791587916879178791887919879208792187922879238792487925879268792787928879298793087931879328793387934879358793687937879388793987940879418794287943879448794587946879478794887949879508795187952879538795487955879568795787958879598796087961879628796387964879658796687967879688796987970879718797287973879748797587976879778797887979879808798187982879838798487985879868798787988879898799087991879928799387994879958799687997879988799988000880018800288003880048800588006880078800888009880108801188012880138801488015880168801788018880198802088021880228802388024880258802688027880288802988030880318803288033880348803588036880378803888039880408804188042880438804488045880468804788048880498805088051880528805388054880558805688057880588805988060880618806288063880648806588066880678806888069880708807188072880738807488075880768807788078880798808088081880828808388084880858808688087880888808988090880918809288093880948809588096880978809888099881008810188102881038810488105881068810788108881098811088111881128811388114881158811688117881188811988120881218812288123881248812588126881278812888129881308813188132881338813488135881368813788138881398814088141881428814388144881458814688147881488814988150881518815288153881548815588156881578815888159881608816188162881638816488165881668816788168881698817088171881728817388174881758817688177881788817988180881818818288183881848818588186881878818888189881908819188192881938819488195881968819788198881998820088201882028820388204882058820688207882088820988210882118821288213882148821588216882178821888219882208822188222882238822488225882268822788228882298823088231882328823388234882358823688237882388823988240882418824288243882448824588246882478824888249882508825188252882538825488255882568825788258882598826088261882628826388264882658826688267882688826988270882718827288273882748827588276882778827888279882808828188282882838828488285882868828788288882898829088291882928829388294882958829688297882988829988300883018830288303883048830588306883078830888309883108831188312883138831488315883168831788318883198832088321883228832388324883258832688327883288832988330883318833288333883348833588336883378833888339883408834188342883438834488345883468834788348883498835088351883528835388354883558835688357883588835988360883618836288363883648836588366883678836888369883708837188372883738837488375883768837788378883798838088381883828838388384883858838688387883888838988390883918839288393883948839588396883978839888399884008840188402884038840488405884068840788408884098841088411884128841388414884158841688417884188841988420884218842288423884248842588426884278842888429884308843188432884338843488435884368843788438884398844088441884428844388444884458844688447884488844988450884518845288453884548845588456884578845888459884608846188462884638846488465884668846788468884698847088471884728847388474884758847688477884788847988480884818848288483884848848588486884878848888489884908849188492884938849488495884968849788498884998850088501885028850388504885058850688507885088850988510885118851288513885148851588516885178851888519885208852188522885238852488525885268852788528885298853088531885328853388534885358853688537885388853988540885418854288543885448854588546885478854888549885508855188552885538855488555885568855788558885598856088561885628856388564885658856688567885688856988570885718857288573885748857588576885778857888579885808858188582885838858488585885868858788588885898859088591885928859388594885958859688597885988859988600886018860288603886048860588606886078860888609886108861188612886138861488615886168861788618886198862088621886228862388624886258862688627886288862988630886318863288633886348863588636886378863888639886408864188642886438864488645886468864788648886498865088651886528865388654886558865688657886588865988660886618866288663886648866588666886678866888669886708867188672886738867488675886768867788678886798868088681886828868388684886858868688687886888868988690886918869288693886948869588696886978869888699887008870188702887038870488705887068870788708887098871088711887128871388714887158871688717887188871988720887218872288723887248872588726887278872888729887308873188732887338873488735887368873788738887398874088741887428874388744887458874688747887488874988750887518875288753887548875588756887578875888759887608876188762887638876488765887668876788768887698877088771887728877388774887758877688777887788877988780887818878288783887848878588786887878878888789887908879188792887938879488795887968879788798887998880088801888028880388804888058880688807888088880988810888118881288813888148881588816888178881888819888208882188822888238882488825888268882788828888298883088831888328883388834888358883688837888388883988840888418884288843888448884588846888478884888849888508885188852888538885488855888568885788858888598886088861888628886388864888658886688867888688886988870888718887288873888748887588876888778887888879888808888188882888838888488885888868888788888888898889088891888928889388894888958889688897888988889988900889018890288903889048890588906889078890888909889108891188912889138891488915889168891788918889198892088921889228892388924889258892688927889288892988930889318893288933889348893588936889378893888939889408894188942889438894488945889468894788948889498895088951889528895388954889558895688957889588895988960889618896288963889648896588966889678896888969889708897188972889738897488975889768897788978889798898088981889828898388984889858898688987889888898988990889918899288993889948899588996889978899888999890008900189002890038900489005890068900789008890098901089011890128901389014890158901689017890188901989020890218902289023890248902589026890278902889029890308903189032890338903489035890368903789038890398904089041890428904389044890458904689047890488904989050890518905289053890548905589056890578905889059890608906189062890638906489065890668906789068890698907089071890728907389074890758907689077890788907989080890818908289083890848908589086890878908889089890908909189092890938909489095890968909789098890998910089101891028910389104891058910689107891088910989110891118911289113891148911589116891178911889119891208912189122891238912489125891268912789128891298913089131891328913389134891358913689137891388913989140891418914289143891448914589146891478914889149891508915189152891538915489155891568915789158891598916089161891628916389164891658916689167891688916989170891718917289173891748917589176891778917889179891808918189182891838918489185891868918789188891898919089191891928919389194891958919689197891988919989200892018920289203892048920589206892078920889209892108921189212892138921489215892168921789218892198922089221892228922389224892258922689227892288922989230892318923289233892348923589236892378923889239892408924189242892438924489245892468924789248892498925089251892528925389254892558925689257892588925989260892618926289263892648926589266892678926889269892708927189272892738927489275892768927789278892798928089281892828928389284892858928689287892888928989290892918929289293892948929589296892978929889299893008930189302893038930489305893068930789308893098931089311893128931389314893158931689317893188931989320893218932289323893248932589326893278932889329893308933189332893338933489335893368933789338893398934089341893428934389344893458934689347893488934989350893518935289353893548935589356893578935889359893608936189362893638936489365893668936789368893698937089371893728937389374893758937689377893788937989380893818938289383893848938589386893878938889389893908939189392893938939489395893968939789398893998940089401894028940389404894058940689407894088940989410894118941289413894148941589416894178941889419894208942189422894238942489425894268942789428894298943089431894328943389434894358943689437894388943989440894418944289443894448944589446894478944889449894508945189452894538945489455894568945789458894598946089461894628946389464894658946689467894688946989470894718947289473894748947589476894778947889479894808948189482894838948489485894868948789488894898949089491894928949389494894958949689497894988949989500895018950289503895048950589506895078950889509895108951189512895138951489515895168951789518895198952089521895228952389524895258952689527895288952989530895318953289533895348953589536895378953889539895408954189542895438954489545895468954789548895498955089551895528955389554895558955689557895588955989560895618956289563895648956589566895678956889569895708957189572895738957489575895768957789578895798958089581895828958389584895858958689587895888958989590895918959289593895948959589596895978959889599896008960189602896038960489605896068960789608896098961089611896128961389614896158961689617896188961989620896218962289623896248962589626896278962889629896308963189632896338963489635896368963789638896398964089641896428964389644896458964689647896488964989650896518965289653896548965589656896578965889659896608966189662896638966489665896668966789668896698967089671896728967389674896758967689677896788967989680896818968289683896848968589686896878968889689896908969189692896938969489695896968969789698896998970089701897028970389704897058970689707897088970989710897118971289713897148971589716897178971889719897208972189722897238972489725897268972789728897298973089731897328973389734897358973689737897388973989740897418974289743897448974589746897478974889749897508975189752897538975489755897568975789758897598976089761897628976389764897658976689767897688976989770897718977289773897748977589776897778977889779897808978189782897838978489785897868978789788897898979089791897928979389794897958979689797897988979989800898018980289803898048980589806898078980889809898108981189812898138981489815898168981789818898198982089821898228982389824898258982689827898288982989830898318983289833898348983589836898378983889839898408984189842898438984489845898468984789848898498985089851898528985389854898558985689857898588985989860898618986289863898648986589866898678986889869898708987189872898738987489875898768987789878898798988089881898828988389884898858988689887898888988989890898918989289893898948989589896898978989889899899008990189902899038990489905899068990789908899098991089911899128991389914899158991689917899188991989920899218992289923899248992589926899278992889929899308993189932899338993489935899368993789938899398994089941899428994389944899458994689947899488994989950899518995289953899548995589956899578995889959899608996189962899638996489965899668996789968899698997089971899728997389974899758997689977899788997989980899818998289983899848998589986899878998889989899908999189992899938999489995899968999789998899999000090001900029000390004900059000690007900089000990010900119001290013900149001590016900179001890019900209002190022900239002490025900269002790028900299003090031900329003390034900359003690037900389003990040900419004290043900449004590046900479004890049900509005190052900539005490055900569005790058900599006090061900629006390064900659006690067900689006990070900719007290073900749007590076900779007890079900809008190082900839008490085900869008790088900899009090091900929009390094900959009690097900989009990100901019010290103901049010590106901079010890109901109011190112901139011490115901169011790118901199012090121901229012390124901259012690127901289012990130901319013290133901349013590136901379013890139901409014190142901439014490145901469014790148901499015090151901529015390154901559015690157901589015990160901619016290163901649016590166901679016890169901709017190172901739017490175901769017790178901799018090181901829018390184901859018690187901889018990190901919019290193901949019590196901979019890199902009020190202902039020490205902069020790208902099021090211902129021390214902159021690217902189021990220902219022290223902249022590226902279022890229902309023190232902339023490235902369023790238902399024090241902429024390244902459024690247902489024990250902519025290253902549025590256902579025890259902609026190262902639026490265902669026790268902699027090271902729027390274902759027690277902789027990280902819028290283902849028590286902879028890289902909029190292902939029490295902969029790298902999030090301903029030390304903059030690307903089030990310903119031290313903149031590316903179031890319903209032190322903239032490325903269032790328903299033090331903329033390334903359033690337903389033990340903419034290343903449034590346903479034890349903509035190352903539035490355903569035790358903599036090361903629036390364903659036690367903689036990370903719037290373903749037590376903779037890379903809038190382903839038490385903869038790388903899039090391903929039390394903959039690397903989039990400904019040290403904049040590406904079040890409904109041190412904139041490415904169041790418904199042090421904229042390424904259042690427904289042990430904319043290433904349043590436904379043890439904409044190442904439044490445904469044790448904499045090451904529045390454904559045690457904589045990460904619046290463904649046590466904679046890469904709047190472904739047490475904769047790478904799048090481904829048390484904859048690487904889048990490904919049290493904949049590496904979049890499905009050190502905039050490505905069050790508905099051090511905129051390514905159051690517905189051990520905219052290523905249052590526905279052890529905309053190532905339053490535905369053790538905399054090541905429054390544905459054690547905489054990550905519055290553905549055590556905579055890559905609056190562905639056490565905669056790568905699057090571905729057390574905759057690577905789057990580905819058290583905849058590586905879058890589905909059190592905939059490595905969059790598905999060090601906029060390604906059060690607906089060990610906119061290613906149061590616906179061890619906209062190622906239062490625906269062790628906299063090631906329063390634906359063690637906389063990640906419064290643906449064590646906479064890649906509065190652906539065490655906569065790658906599066090661906629066390664906659066690667906689066990670906719067290673906749067590676906779067890679906809068190682906839068490685906869068790688906899069090691906929069390694906959069690697906989069990700907019070290703907049070590706907079070890709907109071190712907139071490715907169071790718907199072090721907229072390724907259072690727907289072990730907319073290733907349073590736907379073890739907409074190742907439074490745907469074790748907499075090751907529075390754907559075690757907589075990760907619076290763907649076590766907679076890769907709077190772907739077490775907769077790778907799078090781907829078390784907859078690787907889078990790907919079290793907949079590796907979079890799908009080190802908039080490805908069080790808908099081090811908129081390814908159081690817908189081990820908219082290823908249082590826908279082890829908309083190832908339083490835908369083790838908399084090841908429084390844908459084690847908489084990850908519085290853908549085590856908579085890859908609086190862908639086490865908669086790868908699087090871908729087390874908759087690877908789087990880908819088290883908849088590886908879088890889908909089190892908939089490895908969089790898908999090090901909029090390904909059090690907909089090990910909119091290913909149091590916909179091890919909209092190922909239092490925909269092790928909299093090931909329093390934909359093690937909389093990940909419094290943909449094590946909479094890949909509095190952909539095490955909569095790958909599096090961909629096390964909659096690967909689096990970909719097290973909749097590976909779097890979909809098190982909839098490985909869098790988
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. var BABYLON;
  18. (function (BABYLON) {
  19. /**
  20. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  21. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  22. */
  23. var EffectFallbacks = /** @class */ (function () {
  24. function EffectFallbacks() {
  25. this._defines = {};
  26. this._currentRank = 32;
  27. this._maxRank = -1;
  28. }
  29. /**
  30. * Removes the fallback from the bound mesh.
  31. */
  32. EffectFallbacks.prototype.unBindMesh = function () {
  33. this._mesh = null;
  34. };
  35. /**
  36. * Adds a fallback on the specified property.
  37. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  38. * @param define The name of the define in the shader
  39. */
  40. EffectFallbacks.prototype.addFallback = function (rank, define) {
  41. if (!this._defines[rank]) {
  42. if (rank < this._currentRank) {
  43. this._currentRank = rank;
  44. }
  45. if (rank > this._maxRank) {
  46. this._maxRank = rank;
  47. }
  48. this._defines[rank] = new Array();
  49. }
  50. this._defines[rank].push(define);
  51. };
  52. /**
  53. * Sets the mesh to use CPU skinning when needing to fallback.
  54. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  55. * @param mesh The mesh to use the fallbacks.
  56. */
  57. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  58. this._mesh = mesh;
  59. if (rank < this._currentRank) {
  60. this._currentRank = rank;
  61. }
  62. if (rank > this._maxRank) {
  63. this._maxRank = rank;
  64. }
  65. };
  66. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  67. /**
  68. * Checks to see if more fallbacks are still availible.
  69. */
  70. get: function () {
  71. return this._currentRank <= this._maxRank;
  72. },
  73. enumerable: true,
  74. configurable: true
  75. });
  76. /**
  77. * Removes the defines that shoould be removed when falling back.
  78. * @param currentDefines defines the current define statements for the shader.
  79. * @param effect defines the current effect we try to compile
  80. * @returns The resulting defines with defines of the current rank removed.
  81. */
  82. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  83. // First we try to switch to CPU skinning
  84. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  85. this._mesh.computeBonesUsingShaders = false;
  86. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  87. var scene = this._mesh.getScene();
  88. for (var index = 0; index < scene.meshes.length; index++) {
  89. var otherMesh = scene.meshes[index];
  90. if (!otherMesh.material) {
  91. continue;
  92. }
  93. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  94. continue;
  95. }
  96. if (otherMesh.material.getEffect() === effect) {
  97. otherMesh.computeBonesUsingShaders = false;
  98. }
  99. else {
  100. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  101. var subMesh = _a[_i];
  102. var subMeshEffect = subMesh.effect;
  103. if (subMeshEffect === effect) {
  104. otherMesh.computeBonesUsingShaders = false;
  105. break;
  106. }
  107. }
  108. }
  109. }
  110. }
  111. else {
  112. var currentFallbacks = this._defines[this._currentRank];
  113. if (currentFallbacks) {
  114. for (var index = 0; index < currentFallbacks.length; index++) {
  115. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  116. }
  117. }
  118. this._currentRank++;
  119. }
  120. return currentDefines;
  121. };
  122. return EffectFallbacks;
  123. }());
  124. BABYLON.EffectFallbacks = EffectFallbacks;
  125. /**
  126. * Options to be used when creating an effect.
  127. */
  128. var EffectCreationOptions = /** @class */ (function () {
  129. function EffectCreationOptions() {
  130. }
  131. return EffectCreationOptions;
  132. }());
  133. BABYLON.EffectCreationOptions = EffectCreationOptions;
  134. /**
  135. * Effect containing vertex and fragment shader that can be executed on an object.
  136. */
  137. var Effect = /** @class */ (function () {
  138. /**
  139. * Instantiates an effect.
  140. * An effect can be used to create/manage/execute vertex and fragment shaders.
  141. * @param baseName Name of the effect.
  142. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  143. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  144. * @param samplers List of sampler variables that will be passed to the shader.
  145. * @param engine Engine to be used to render the effect
  146. * @param defines Define statements to be added to the shader.
  147. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  148. * @param onCompiled Callback that will be called when the shader is compiled.
  149. * @param onError Callback that will be called if an error occurs during shader compilation.
  150. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  151. */
  152. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  153. if (samplers === void 0) { samplers = null; }
  154. if (defines === void 0) { defines = null; }
  155. if (fallbacks === void 0) { fallbacks = null; }
  156. if (onCompiled === void 0) { onCompiled = null; }
  157. if (onError === void 0) { onError = null; }
  158. var _this = this;
  159. /**
  160. * Unique ID of the effect.
  161. */
  162. this.uniqueId = 0;
  163. /**
  164. * Observable that will be called when the shader is compiled.
  165. */
  166. this.onCompileObservable = new BABYLON.Observable();
  167. /**
  168. * Observable that will be called if an error occurs during shader compilation.
  169. */
  170. this.onErrorObservable = new BABYLON.Observable();
  171. /**
  172. * Observable that will be called when effect is bound.
  173. */
  174. this.onBindObservable = new BABYLON.Observable();
  175. this._uniformBuffersNames = {};
  176. this._isReady = false;
  177. this._compilationError = "";
  178. this.name = baseName;
  179. if (attributesNamesOrOptions.attributes) {
  180. var options = attributesNamesOrOptions;
  181. this._engine = uniformsNamesOrEngine;
  182. this._attributesNames = options.attributes;
  183. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  184. this._samplers = options.samplers;
  185. this.defines = options.defines;
  186. this.onError = options.onError;
  187. this.onCompiled = options.onCompiled;
  188. this._fallbacks = options.fallbacks;
  189. this._indexParameters = options.indexParameters;
  190. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  191. if (options.uniformBuffersNames) {
  192. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  193. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  194. }
  195. }
  196. }
  197. else {
  198. this._engine = engine;
  199. this.defines = defines;
  200. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  201. this._samplers = samplers;
  202. this._attributesNames = attributesNamesOrOptions;
  203. this.onError = onError;
  204. this.onCompiled = onCompiled;
  205. this._indexParameters = indexParameters;
  206. this._fallbacks = fallbacks;
  207. }
  208. this.uniqueId = Effect._uniqueIdSeed++;
  209. var vertexSource;
  210. var fragmentSource;
  211. if (baseName.vertexElement) {
  212. vertexSource = document.getElementById(baseName.vertexElement);
  213. if (!vertexSource) {
  214. vertexSource = baseName.vertexElement;
  215. }
  216. }
  217. else {
  218. vertexSource = baseName.vertex || baseName;
  219. }
  220. if (baseName.fragmentElement) {
  221. fragmentSource = document.getElementById(baseName.fragmentElement);
  222. if (!fragmentSource) {
  223. fragmentSource = baseName.fragmentElement;
  224. }
  225. }
  226. else {
  227. fragmentSource = baseName.fragment || baseName;
  228. }
  229. var finalVertexCode;
  230. this._loadVertexShaderAsync(vertexSource)
  231. .then(function (vertexCode) {
  232. return _this._processIncludesAsync(vertexCode);
  233. })
  234. .then(function (vertexCodeWithIncludes) {
  235. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  236. return _this._loadFragmentShaderAsync(fragmentSource);
  237. })
  238. .then(function (fragmentCode) {
  239. return _this._processIncludesAsync(fragmentCode);
  240. })
  241. .then(function (fragmentCodeWithIncludes) {
  242. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  243. if (baseName) {
  244. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  245. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  246. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  247. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  248. }
  249. else {
  250. _this._vertexSourceCode = finalVertexCode;
  251. _this._fragmentSourceCode = migratedFragmentCode;
  252. }
  253. _this._prepareEffect();
  254. });
  255. }
  256. Object.defineProperty(Effect.prototype, "key", {
  257. /**
  258. * Unique key for this effect
  259. */
  260. get: function () {
  261. return this._key;
  262. },
  263. enumerable: true,
  264. configurable: true
  265. });
  266. /**
  267. * If the effect has been compiled and prepared.
  268. * @returns if the effect is compiled and prepared.
  269. */
  270. Effect.prototype.isReady = function () {
  271. return this._isReady;
  272. };
  273. /**
  274. * The engine the effect was initialized with.
  275. * @returns the engine.
  276. */
  277. Effect.prototype.getEngine = function () {
  278. return this._engine;
  279. };
  280. /**
  281. * The compiled webGL program for the effect
  282. * @returns the webGL program.
  283. */
  284. Effect.prototype.getProgram = function () {
  285. return this._program;
  286. };
  287. /**
  288. * The set of names of attribute variables for the shader.
  289. * @returns An array of attribute names.
  290. */
  291. Effect.prototype.getAttributesNames = function () {
  292. return this._attributesNames;
  293. };
  294. /**
  295. * Returns the attribute at the given index.
  296. * @param index The index of the attribute.
  297. * @returns The location of the attribute.
  298. */
  299. Effect.prototype.getAttributeLocation = function (index) {
  300. return this._attributes[index];
  301. };
  302. /**
  303. * Returns the attribute based on the name of the variable.
  304. * @param name of the attribute to look up.
  305. * @returns the attribute location.
  306. */
  307. Effect.prototype.getAttributeLocationByName = function (name) {
  308. var index = this._attributesNames.indexOf(name);
  309. return this._attributes[index];
  310. };
  311. /**
  312. * The number of attributes.
  313. * @returns the numnber of attributes.
  314. */
  315. Effect.prototype.getAttributesCount = function () {
  316. return this._attributes.length;
  317. };
  318. /**
  319. * Gets the index of a uniform variable.
  320. * @param uniformName of the uniform to look up.
  321. * @returns the index.
  322. */
  323. Effect.prototype.getUniformIndex = function (uniformName) {
  324. return this._uniformsNames.indexOf(uniformName);
  325. };
  326. /**
  327. * Returns the attribute based on the name of the variable.
  328. * @param uniformName of the uniform to look up.
  329. * @returns the location of the uniform.
  330. */
  331. Effect.prototype.getUniform = function (uniformName) {
  332. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  333. };
  334. /**
  335. * Returns an array of sampler variable names
  336. * @returns The array of sampler variable neames.
  337. */
  338. Effect.prototype.getSamplers = function () {
  339. return this._samplers;
  340. };
  341. /**
  342. * The error from the last compilation.
  343. * @returns the error string.
  344. */
  345. Effect.prototype.getCompilationError = function () {
  346. return this._compilationError;
  347. };
  348. /**
  349. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  350. * @param func The callback to be used.
  351. */
  352. Effect.prototype.executeWhenCompiled = function (func) {
  353. if (this.isReady()) {
  354. func(this);
  355. return;
  356. }
  357. this.onCompileObservable.add(function (effect) {
  358. func(effect);
  359. });
  360. };
  361. /** @ignore */
  362. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  363. if (BABYLON.Tools.IsWindowObjectExist()) {
  364. // DOM element ?
  365. if (vertex instanceof HTMLElement) {
  366. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  367. return Promise.resolve(vertexCode);
  368. }
  369. }
  370. // Base64 encoded ?
  371. if (vertex.substr(0, 7) === "base64:") {
  372. var vertexBinary = window.atob(vertex.substr(7));
  373. return Promise.resolve(vertexBinary);
  374. }
  375. // Is in local store ?
  376. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  377. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  378. }
  379. var vertexShaderUrl;
  380. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  381. vertexShaderUrl = vertex;
  382. }
  383. else {
  384. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  385. }
  386. // Vertex shader
  387. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  388. };
  389. /** @ignore */
  390. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  391. if (BABYLON.Tools.IsWindowObjectExist()) {
  392. // DOM element ?
  393. if (fragment instanceof HTMLElement) {
  394. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  395. return Promise.resolve(fragmentCode);
  396. }
  397. }
  398. // Base64 encoded ?
  399. if (fragment.substr(0, 7) === "base64:") {
  400. var fragmentBinary = window.atob(fragment.substr(7));
  401. return Promise.resolve(fragmentBinary);
  402. }
  403. // Is in local store ?
  404. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  405. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  406. }
  407. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  408. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  409. }
  410. var fragmentShaderUrl;
  411. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  412. fragmentShaderUrl = fragment;
  413. }
  414. else {
  415. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  416. }
  417. // Fragment shader
  418. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  419. };
  420. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  421. // Rebuild shaders source code
  422. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  423. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  424. vertexCode = prefix + vertexCode;
  425. fragmentCode = prefix + fragmentCode;
  426. // Number lines of shaders source code
  427. var i = 2;
  428. var regex = /\n/gm;
  429. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  430. i = 2;
  431. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  432. // Dump shaders name and formatted source code
  433. if (this.name.vertexElement) {
  434. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  435. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  436. }
  437. else if (this.name.vertex) {
  438. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  439. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  440. }
  441. else {
  442. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  443. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  444. }
  445. };
  446. ;
  447. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  448. var preparedSourceCode = this._processPrecision(sourceCode);
  449. if (this._engine.webGLVersion == 1) {
  450. return preparedSourceCode;
  451. }
  452. // Already converted
  453. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  454. return preparedSourceCode.replace("#version 300 es", "");
  455. }
  456. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  457. // Remove extensions
  458. // #extension GL_OES_standard_derivatives : enable
  459. // #extension GL_EXT_shader_texture_lod : enable
  460. // #extension GL_EXT_frag_depth : enable
  461. // #extension GL_EXT_draw_buffers : require
  462. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  463. var result = preparedSourceCode.replace(regex, "");
  464. // Migrate to GLSL v300
  465. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  466. result = result.replace(/attribute[ \t]/g, "in ");
  467. result = result.replace(/[ \t]attribute/g, " in");
  468. if (isFragment) {
  469. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  470. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  471. result = result.replace(/texture2D\s*\(/g, "texture(");
  472. result = result.replace(/textureCube\s*\(/g, "texture(");
  473. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  474. result = result.replace(/gl_FragColor/g, "glFragColor");
  475. result = result.replace(/gl_FragData/g, "glFragData");
  476. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  477. }
  478. return result;
  479. };
  480. Effect.prototype._processIncludesAsync = function (sourceCode) {
  481. var _this = this;
  482. return new Promise(function (resolve, reject) {
  483. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  484. var match = regex.exec(sourceCode);
  485. var returnValue = sourceCode;
  486. while (match != null) {
  487. var includeFile = match[1];
  488. // Uniform declaration
  489. if (includeFile.indexOf("__decl__") !== -1) {
  490. includeFile = includeFile.replace(/__decl__/, "");
  491. if (_this._engine.supportsUniformBuffers) {
  492. includeFile = includeFile.replace(/Vertex/, "Ubo");
  493. includeFile = includeFile.replace(/Fragment/, "Ubo");
  494. }
  495. includeFile = includeFile + "Declaration";
  496. }
  497. if (Effect.IncludesShadersStore[includeFile]) {
  498. // Substitution
  499. var includeContent = Effect.IncludesShadersStore[includeFile];
  500. if (match[2]) {
  501. var splits = match[3].split(",");
  502. for (var index = 0; index < splits.length; index += 2) {
  503. var source = new RegExp(splits[index], "g");
  504. var dest = splits[index + 1];
  505. includeContent = includeContent.replace(source, dest);
  506. }
  507. }
  508. if (match[4]) {
  509. var indexString = match[5];
  510. if (indexString.indexOf("..") !== -1) {
  511. var indexSplits = indexString.split("..");
  512. var minIndex = parseInt(indexSplits[0]);
  513. var maxIndex = parseInt(indexSplits[1]);
  514. var sourceIncludeContent = includeContent.slice(0);
  515. includeContent = "";
  516. if (isNaN(maxIndex)) {
  517. maxIndex = _this._indexParameters[indexSplits[1]];
  518. }
  519. for (var i = minIndex; i < maxIndex; i++) {
  520. if (!_this._engine.supportsUniformBuffers) {
  521. // Ubo replacement
  522. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  523. return p1 + "{X}";
  524. });
  525. }
  526. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  527. }
  528. }
  529. else {
  530. if (!_this._engine.supportsUniformBuffers) {
  531. // Ubo replacement
  532. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  533. return p1 + "{X}";
  534. });
  535. }
  536. includeContent = includeContent.replace(/\{X\}/g, indexString);
  537. }
  538. }
  539. // Replace
  540. returnValue = returnValue.replace(match[0], includeContent);
  541. }
  542. else {
  543. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  544. _this._engine._loadFileAsync(includeShaderUrl)
  545. .then(function (fileContent) {
  546. Effect.IncludesShadersStore[includeFile] = fileContent;
  547. return _this._processIncludesAsync(returnValue);
  548. })
  549. .then(function (returnValue) {
  550. resolve(returnValue);
  551. });
  552. return;
  553. }
  554. match = regex.exec(sourceCode);
  555. }
  556. resolve(returnValue);
  557. });
  558. };
  559. Effect.prototype._processPrecision = function (source) {
  560. if (source.indexOf("precision highp float") === -1) {
  561. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  562. source = "precision mediump float;\n" + source;
  563. }
  564. else {
  565. source = "precision highp float;\n" + source;
  566. }
  567. }
  568. else {
  569. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  570. source = source.replace("precision highp float", "precision mediump float");
  571. }
  572. }
  573. return source;
  574. };
  575. /**
  576. * Recompiles the webGL program
  577. * @param vertexSourceCode The source code for the vertex shader.
  578. * @param fragmentSourceCode The source code for the fragment shader.
  579. * @param onCompiled Callback called when completed.
  580. * @param onError Callback called on error.
  581. */
  582. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  583. var _this = this;
  584. this._isReady = false;
  585. this._vertexSourceCodeOverride = vertexSourceCode;
  586. this._fragmentSourceCodeOverride = fragmentSourceCode;
  587. this.onError = function (effect, error) {
  588. if (onError) {
  589. onError(error);
  590. }
  591. };
  592. this.onCompiled = function () {
  593. var scenes = _this.getEngine().scenes;
  594. for (var i = 0; i < scenes.length; i++) {
  595. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  596. }
  597. if (onCompiled) {
  598. onCompiled(_this._program);
  599. }
  600. };
  601. this._fallbacks = null;
  602. this._prepareEffect();
  603. };
  604. /**
  605. * Gets the uniform locations of the the specified variable names
  606. * @param names THe names of the variables to lookup.
  607. * @returns Array of locations in the same order as variable names.
  608. */
  609. Effect.prototype.getSpecificUniformLocations = function (names) {
  610. var engine = this._engine;
  611. return engine.getUniforms(this._program, names);
  612. };
  613. /**
  614. * Prepares the effect
  615. */
  616. Effect.prototype._prepareEffect = function () {
  617. var attributesNames = this._attributesNames;
  618. var defines = this.defines;
  619. var fallbacks = this._fallbacks;
  620. this._valueCache = {};
  621. var previousProgram = this._program;
  622. try {
  623. var engine = this._engine;
  624. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  625. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  626. }
  627. else {
  628. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  629. }
  630. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  631. if (engine.supportsUniformBuffers) {
  632. for (var name in this._uniformBuffersNames) {
  633. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  634. }
  635. }
  636. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  637. this._attributes = engine.getAttributes(this._program, attributesNames);
  638. var index;
  639. for (index = 0; index < this._samplers.length; index++) {
  640. var sampler = this.getUniform(this._samplers[index]);
  641. if (sampler == null) {
  642. this._samplers.splice(index, 1);
  643. index--;
  644. }
  645. }
  646. engine.bindSamplers(this);
  647. this._compilationError = "";
  648. this._isReady = true;
  649. if (this.onCompiled) {
  650. this.onCompiled(this);
  651. }
  652. this.onCompileObservable.notifyObservers(this);
  653. this.onCompileObservable.clear();
  654. // Unbind mesh reference in fallbacks
  655. if (this._fallbacks) {
  656. this._fallbacks.unBindMesh();
  657. }
  658. if (previousProgram) {
  659. this.getEngine()._deleteProgram(previousProgram);
  660. }
  661. }
  662. catch (e) {
  663. this._compilationError = e.message;
  664. // Let's go through fallbacks then
  665. BABYLON.Tools.Error("Unable to compile effect:");
  666. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  667. return " " + uniform;
  668. }));
  669. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  670. return " " + attribute;
  671. }));
  672. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  673. BABYLON.Tools.Error("Error: " + this._compilationError);
  674. if (previousProgram) {
  675. this._program = previousProgram;
  676. this._isReady = true;
  677. if (this.onError) {
  678. this.onError(this, this._compilationError);
  679. }
  680. this.onErrorObservable.notifyObservers(this);
  681. }
  682. if (fallbacks && fallbacks.isMoreFallbacks) {
  683. BABYLON.Tools.Error("Trying next fallback.");
  684. this.defines = fallbacks.reduce(this.defines, this);
  685. this._prepareEffect();
  686. }
  687. else {
  688. if (this.onError) {
  689. this.onError(this, this._compilationError);
  690. }
  691. this.onErrorObservable.notifyObservers(this);
  692. this.onErrorObservable.clear();
  693. // Unbind mesh reference in fallbacks
  694. if (this._fallbacks) {
  695. this._fallbacks.unBindMesh();
  696. }
  697. }
  698. }
  699. };
  700. Object.defineProperty(Effect.prototype, "isSupported", {
  701. /**
  702. * Checks if the effect is supported. (Must be called after compilation)
  703. */
  704. get: function () {
  705. return this._compilationError === "";
  706. },
  707. enumerable: true,
  708. configurable: true
  709. });
  710. /**
  711. * Binds a texture to the engine to be used as output of the shader.
  712. * @param channel Name of the output variable.
  713. * @param texture Texture to bind.
  714. */
  715. Effect.prototype._bindTexture = function (channel, texture) {
  716. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  717. };
  718. /**
  719. * Sets a texture on the engine to be used in the shader.
  720. * @param channel Name of the sampler variable.
  721. * @param texture Texture to set.
  722. */
  723. Effect.prototype.setTexture = function (channel, texture) {
  724. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  725. };
  726. /**
  727. * Sets an array of textures on the engine to be used in the shader.
  728. * @param channel Name of the variable.
  729. * @param textures Textures to set.
  730. */
  731. Effect.prototype.setTextureArray = function (channel, textures) {
  732. if (this._samplers.indexOf(channel + "Ex") === -1) {
  733. var initialPos = this._samplers.indexOf(channel);
  734. for (var index = 1; index < textures.length; index++) {
  735. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  736. }
  737. }
  738. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  739. };
  740. /**
  741. * 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)
  742. * @param channel Name of the sampler variable.
  743. * @param postProcess Post process to get the input texture from.
  744. */
  745. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  746. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  747. };
  748. /** @ignore */
  749. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  750. var cache = this._valueCache[uniformName];
  751. var flag = matrix.updateFlag;
  752. if (cache !== undefined && cache === flag) {
  753. return false;
  754. }
  755. this._valueCache[uniformName] = flag;
  756. return true;
  757. };
  758. /** @ignore */
  759. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  760. var cache = this._valueCache[uniformName];
  761. if (!cache) {
  762. cache = [x, y];
  763. this._valueCache[uniformName] = cache;
  764. return true;
  765. }
  766. var changed = false;
  767. if (cache[0] !== x) {
  768. cache[0] = x;
  769. changed = true;
  770. }
  771. if (cache[1] !== y) {
  772. cache[1] = y;
  773. changed = true;
  774. }
  775. return changed;
  776. };
  777. /** @ignore */
  778. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  779. var cache = this._valueCache[uniformName];
  780. if (!cache) {
  781. cache = [x, y, z];
  782. this._valueCache[uniformName] = cache;
  783. return true;
  784. }
  785. var changed = false;
  786. if (cache[0] !== x) {
  787. cache[0] = x;
  788. changed = true;
  789. }
  790. if (cache[1] !== y) {
  791. cache[1] = y;
  792. changed = true;
  793. }
  794. if (cache[2] !== z) {
  795. cache[2] = z;
  796. changed = true;
  797. }
  798. return changed;
  799. };
  800. /** @ignore */
  801. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  802. var cache = this._valueCache[uniformName];
  803. if (!cache) {
  804. cache = [x, y, z, w];
  805. this._valueCache[uniformName] = cache;
  806. return true;
  807. }
  808. var changed = false;
  809. if (cache[0] !== x) {
  810. cache[0] = x;
  811. changed = true;
  812. }
  813. if (cache[1] !== y) {
  814. cache[1] = y;
  815. changed = true;
  816. }
  817. if (cache[2] !== z) {
  818. cache[2] = z;
  819. changed = true;
  820. }
  821. if (cache[3] !== w) {
  822. cache[3] = w;
  823. changed = true;
  824. }
  825. return changed;
  826. };
  827. /**
  828. * Binds a buffer to a uniform.
  829. * @param buffer Buffer to bind.
  830. * @param name Name of the uniform variable to bind to.
  831. */
  832. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  833. var bufferName = this._uniformBuffersNames[name];
  834. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  835. return;
  836. }
  837. Effect._baseCache[bufferName] = buffer;
  838. this._engine.bindUniformBufferBase(buffer, bufferName);
  839. };
  840. /**
  841. * Binds block to a uniform.
  842. * @param blockName Name of the block to bind.
  843. * @param index Index to bind.
  844. */
  845. Effect.prototype.bindUniformBlock = function (blockName, index) {
  846. this._engine.bindUniformBlock(this._program, blockName, index);
  847. };
  848. /**
  849. * Sets an interger value on a uniform variable.
  850. * @param uniformName Name of the variable.
  851. * @param value Value to be set.
  852. * @returns this effect.
  853. */
  854. Effect.prototype.setInt = function (uniformName, value) {
  855. var cache = this._valueCache[uniformName];
  856. if (cache !== undefined && cache === value)
  857. return this;
  858. this._valueCache[uniformName] = value;
  859. this._engine.setInt(this.getUniform(uniformName), value);
  860. return this;
  861. };
  862. /**
  863. * Sets an int array on a uniform variable.
  864. * @param uniformName Name of the variable.
  865. * @param array array to be set.
  866. * @returns this effect.
  867. */
  868. Effect.prototype.setIntArray = function (uniformName, array) {
  869. this._valueCache[uniformName] = null;
  870. this._engine.setIntArray(this.getUniform(uniformName), array);
  871. return this;
  872. };
  873. /**
  874. * 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)
  875. * @param uniformName Name of the variable.
  876. * @param array array to be set.
  877. * @returns this effect.
  878. */
  879. Effect.prototype.setIntArray2 = function (uniformName, array) {
  880. this._valueCache[uniformName] = null;
  881. this._engine.setIntArray2(this.getUniform(uniformName), array);
  882. return this;
  883. };
  884. /**
  885. * 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)
  886. * @param uniformName Name of the variable.
  887. * @param array array to be set.
  888. * @returns this effect.
  889. */
  890. Effect.prototype.setIntArray3 = function (uniformName, array) {
  891. this._valueCache[uniformName] = null;
  892. this._engine.setIntArray3(this.getUniform(uniformName), array);
  893. return this;
  894. };
  895. /**
  896. * 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)
  897. * @param uniformName Name of the variable.
  898. * @param array array to be set.
  899. * @returns this effect.
  900. */
  901. Effect.prototype.setIntArray4 = function (uniformName, array) {
  902. this._valueCache[uniformName] = null;
  903. this._engine.setIntArray4(this.getUniform(uniformName), array);
  904. return this;
  905. };
  906. /**
  907. * Sets an float array on a uniform variable.
  908. * @param uniformName Name of the variable.
  909. * @param array array to be set.
  910. * @returns this effect.
  911. */
  912. Effect.prototype.setFloatArray = function (uniformName, array) {
  913. this._valueCache[uniformName] = null;
  914. this._engine.setFloatArray(this.getUniform(uniformName), array);
  915. return this;
  916. };
  917. /**
  918. * 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)
  919. * @param uniformName Name of the variable.
  920. * @param array array to be set.
  921. * @returns this effect.
  922. */
  923. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  924. this._valueCache[uniformName] = null;
  925. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  926. return this;
  927. };
  928. /**
  929. * 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)
  930. * @param uniformName Name of the variable.
  931. * @param array array to be set.
  932. * @returns this effect.
  933. */
  934. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  935. this._valueCache[uniformName] = null;
  936. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  937. return this;
  938. };
  939. /**
  940. * 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)
  941. * @param uniformName Name of the variable.
  942. * @param array array to be set.
  943. * @returns this effect.
  944. */
  945. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  946. this._valueCache[uniformName] = null;
  947. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  948. return this;
  949. };
  950. /**
  951. * Sets an array on a uniform variable.
  952. * @param uniformName Name of the variable.
  953. * @param array array to be set.
  954. * @returns this effect.
  955. */
  956. Effect.prototype.setArray = function (uniformName, array) {
  957. this._valueCache[uniformName] = null;
  958. this._engine.setArray(this.getUniform(uniformName), array);
  959. return this;
  960. };
  961. /**
  962. * 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)
  963. * @param uniformName Name of the variable.
  964. * @param array array to be set.
  965. * @returns this effect.
  966. */
  967. Effect.prototype.setArray2 = function (uniformName, array) {
  968. this._valueCache[uniformName] = null;
  969. this._engine.setArray2(this.getUniform(uniformName), array);
  970. return this;
  971. };
  972. /**
  973. * 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)
  974. * @param uniformName Name of the variable.
  975. * @param array array to be set.
  976. * @returns this effect.
  977. */
  978. Effect.prototype.setArray3 = function (uniformName, array) {
  979. this._valueCache[uniformName] = null;
  980. this._engine.setArray3(this.getUniform(uniformName), array);
  981. return this;
  982. };
  983. /**
  984. * 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)
  985. * @param uniformName Name of the variable.
  986. * @param array array to be set.
  987. * @returns this effect.
  988. */
  989. Effect.prototype.setArray4 = function (uniformName, array) {
  990. this._valueCache[uniformName] = null;
  991. this._engine.setArray4(this.getUniform(uniformName), array);
  992. return this;
  993. };
  994. /**
  995. * Sets matrices on a uniform variable.
  996. * @param uniformName Name of the variable.
  997. * @param matrices matrices to be set.
  998. * @returns this effect.
  999. */
  1000. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1001. if (!matrices) {
  1002. return this;
  1003. }
  1004. this._valueCache[uniformName] = null;
  1005. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1006. return this;
  1007. };
  1008. /**
  1009. * Sets matrix on a uniform variable.
  1010. * @param uniformName Name of the variable.
  1011. * @param matrix matrix to be set.
  1012. * @returns this effect.
  1013. */
  1014. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1015. if (this._cacheMatrix(uniformName, matrix)) {
  1016. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1017. }
  1018. return this;
  1019. };
  1020. /**
  1021. * 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)
  1022. * @param uniformName Name of the variable.
  1023. * @param matrix matrix to be set.
  1024. * @returns this effect.
  1025. */
  1026. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1027. this._valueCache[uniformName] = null;
  1028. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1029. return this;
  1030. };
  1031. /**
  1032. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1033. * @param uniformName Name of the variable.
  1034. * @param matrix matrix to be set.
  1035. * @returns this effect.
  1036. */
  1037. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1038. this._valueCache[uniformName] = null;
  1039. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1040. return this;
  1041. };
  1042. /**
  1043. * Sets a float on a uniform variable.
  1044. * @param uniformName Name of the variable.
  1045. * @param value value to be set.
  1046. * @returns this effect.
  1047. */
  1048. Effect.prototype.setFloat = function (uniformName, value) {
  1049. var cache = this._valueCache[uniformName];
  1050. if (cache !== undefined && cache === value)
  1051. return this;
  1052. this._valueCache[uniformName] = value;
  1053. this._engine.setFloat(this.getUniform(uniformName), value);
  1054. return this;
  1055. };
  1056. /**
  1057. * Sets a boolean on a uniform variable.
  1058. * @param uniformName Name of the variable.
  1059. * @param bool value to be set.
  1060. * @returns this effect.
  1061. */
  1062. Effect.prototype.setBool = function (uniformName, bool) {
  1063. var cache = this._valueCache[uniformName];
  1064. if (cache !== undefined && cache === bool)
  1065. return this;
  1066. this._valueCache[uniformName] = bool;
  1067. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1068. return this;
  1069. };
  1070. /**
  1071. * Sets a Vector2 on a uniform variable.
  1072. * @param uniformName Name of the variable.
  1073. * @param vector2 vector2 to be set.
  1074. * @returns this effect.
  1075. */
  1076. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1077. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1078. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1079. }
  1080. return this;
  1081. };
  1082. /**
  1083. * Sets a float2 on a uniform variable.
  1084. * @param uniformName Name of the variable.
  1085. * @param x First float in float2.
  1086. * @param y Second float in float2.
  1087. * @returns this effect.
  1088. */
  1089. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1090. if (this._cacheFloat2(uniformName, x, y)) {
  1091. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1092. }
  1093. return this;
  1094. };
  1095. /**
  1096. * Sets a Vector3 on a uniform variable.
  1097. * @param uniformName Name of the variable.
  1098. * @param vector3 Value to be set.
  1099. * @returns this effect.
  1100. */
  1101. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1102. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1103. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1104. }
  1105. return this;
  1106. };
  1107. /**
  1108. * Sets a float3 on a uniform variable.
  1109. * @param uniformName Name of the variable.
  1110. * @param x First float in float3.
  1111. * @param y Second float in float3.
  1112. * @param z Third float in float3.
  1113. * @returns this effect.
  1114. */
  1115. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1116. if (this._cacheFloat3(uniformName, x, y, z)) {
  1117. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1118. }
  1119. return this;
  1120. };
  1121. /**
  1122. * Sets a Vector4 on a uniform variable.
  1123. * @param uniformName Name of the variable.
  1124. * @param vector4 Value to be set.
  1125. * @returns this effect.
  1126. */
  1127. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1128. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1129. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1130. }
  1131. return this;
  1132. };
  1133. /**
  1134. * Sets a float4 on a uniform variable.
  1135. * @param uniformName Name of the variable.
  1136. * @param x First float in float4.
  1137. * @param y Second float in float4.
  1138. * @param z Third float in float4.
  1139. * @param w Fourth float in float4.
  1140. * @returns this effect.
  1141. */
  1142. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1143. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1144. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1145. }
  1146. return this;
  1147. };
  1148. /**
  1149. * Sets a Color3 on a uniform variable.
  1150. * @param uniformName Name of the variable.
  1151. * @param color3 Value to be set.
  1152. * @returns this effect.
  1153. */
  1154. Effect.prototype.setColor3 = function (uniformName, color3) {
  1155. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1156. this._engine.setColor3(this.getUniform(uniformName), color3);
  1157. }
  1158. return this;
  1159. };
  1160. /**
  1161. * Sets a Color4 on a uniform variable.
  1162. * @param uniformName Name of the variable.
  1163. * @param color3 Value to be set.
  1164. * @param alpha Alpha value to be set.
  1165. * @returns this effect.
  1166. */
  1167. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1168. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1169. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1170. }
  1171. return this;
  1172. };
  1173. /**
  1174. * Sets a Color4 on a uniform variable
  1175. * @param uniformName defines the name of the variable
  1176. * @param color4 defines the value to be set
  1177. * @returns this effect.
  1178. */
  1179. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1180. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1181. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1182. }
  1183. return this;
  1184. };
  1185. /**
  1186. * Resets the cache of effects.
  1187. */
  1188. Effect.ResetCache = function () {
  1189. Effect._baseCache = {};
  1190. };
  1191. Effect._uniqueIdSeed = 0;
  1192. Effect._baseCache = {};
  1193. // Statics
  1194. /**
  1195. * Store of each shader (The can be looked up using effect.key)
  1196. */
  1197. Effect.ShadersStore = {};
  1198. /**
  1199. * Store of each included file for a shader (The can be looked up using effect.key)
  1200. */
  1201. Effect.IncludesShadersStore = {};
  1202. return Effect;
  1203. }());
  1204. BABYLON.Effect = Effect;
  1205. })(BABYLON || (BABYLON = {}));
  1206. //# sourceMappingURL=babylon.effect.js.map
  1207. //# sourceMappingURL=babylon.types.js.map
  1208. var BABYLON;
  1209. (function (BABYLON) {
  1210. var KeyboardEventTypes = /** @class */ (function () {
  1211. function KeyboardEventTypes() {
  1212. }
  1213. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1214. get: function () {
  1215. return KeyboardEventTypes._KEYDOWN;
  1216. },
  1217. enumerable: true,
  1218. configurable: true
  1219. });
  1220. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1221. get: function () {
  1222. return KeyboardEventTypes._KEYUP;
  1223. },
  1224. enumerable: true,
  1225. configurable: true
  1226. });
  1227. KeyboardEventTypes._KEYDOWN = 0x01;
  1228. KeyboardEventTypes._KEYUP = 0x02;
  1229. return KeyboardEventTypes;
  1230. }());
  1231. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1232. var KeyboardInfo = /** @class */ (function () {
  1233. function KeyboardInfo(type, event) {
  1234. this.type = type;
  1235. this.event = event;
  1236. }
  1237. return KeyboardInfo;
  1238. }());
  1239. BABYLON.KeyboardInfo = KeyboardInfo;
  1240. /**
  1241. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1242. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1243. */
  1244. var KeyboardInfoPre = /** @class */ (function (_super) {
  1245. __extends(KeyboardInfoPre, _super);
  1246. function KeyboardInfoPre(type, event) {
  1247. var _this = _super.call(this, type, event) || this;
  1248. _this.skipOnPointerObservable = false;
  1249. return _this;
  1250. }
  1251. return KeyboardInfoPre;
  1252. }(KeyboardInfo));
  1253. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1254. })(BABYLON || (BABYLON = {}));
  1255. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1256. var BABYLON;
  1257. (function (BABYLON) {
  1258. var PointerEventTypes = /** @class */ (function () {
  1259. function PointerEventTypes() {
  1260. }
  1261. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1262. get: function () {
  1263. return PointerEventTypes._POINTERDOWN;
  1264. },
  1265. enumerable: true,
  1266. configurable: true
  1267. });
  1268. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1269. get: function () {
  1270. return PointerEventTypes._POINTERUP;
  1271. },
  1272. enumerable: true,
  1273. configurable: true
  1274. });
  1275. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1276. get: function () {
  1277. return PointerEventTypes._POINTERMOVE;
  1278. },
  1279. enumerable: true,
  1280. configurable: true
  1281. });
  1282. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1283. get: function () {
  1284. return PointerEventTypes._POINTERWHEEL;
  1285. },
  1286. enumerable: true,
  1287. configurable: true
  1288. });
  1289. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1290. get: function () {
  1291. return PointerEventTypes._POINTERPICK;
  1292. },
  1293. enumerable: true,
  1294. configurable: true
  1295. });
  1296. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1297. get: function () {
  1298. return PointerEventTypes._POINTERTAP;
  1299. },
  1300. enumerable: true,
  1301. configurable: true
  1302. });
  1303. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1304. get: function () {
  1305. return PointerEventTypes._POINTERDOUBLETAP;
  1306. },
  1307. enumerable: true,
  1308. configurable: true
  1309. });
  1310. PointerEventTypes._POINTERDOWN = 0x01;
  1311. PointerEventTypes._POINTERUP = 0x02;
  1312. PointerEventTypes._POINTERMOVE = 0x04;
  1313. PointerEventTypes._POINTERWHEEL = 0x08;
  1314. PointerEventTypes._POINTERPICK = 0x10;
  1315. PointerEventTypes._POINTERTAP = 0x20;
  1316. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1317. return PointerEventTypes;
  1318. }());
  1319. BABYLON.PointerEventTypes = PointerEventTypes;
  1320. var PointerInfoBase = /** @class */ (function () {
  1321. function PointerInfoBase(type, event) {
  1322. this.type = type;
  1323. this.event = event;
  1324. }
  1325. return PointerInfoBase;
  1326. }());
  1327. BABYLON.PointerInfoBase = PointerInfoBase;
  1328. /**
  1329. * This class is used to store pointer related info for the onPrePointerObservable event.
  1330. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1331. */
  1332. var PointerInfoPre = /** @class */ (function (_super) {
  1333. __extends(PointerInfoPre, _super);
  1334. function PointerInfoPre(type, event, localX, localY) {
  1335. var _this = _super.call(this, type, event) || this;
  1336. _this.skipOnPointerObservable = false;
  1337. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1338. return _this;
  1339. }
  1340. return PointerInfoPre;
  1341. }(PointerInfoBase));
  1342. BABYLON.PointerInfoPre = PointerInfoPre;
  1343. /**
  1344. * This type contains all the data related to a pointer event in Babylon.js.
  1345. * 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.
  1346. */
  1347. var PointerInfo = /** @class */ (function (_super) {
  1348. __extends(PointerInfo, _super);
  1349. function PointerInfo(type, event, pickInfo) {
  1350. var _this = _super.call(this, type, event) || this;
  1351. _this.pickInfo = pickInfo;
  1352. return _this;
  1353. }
  1354. return PointerInfo;
  1355. }(PointerInfoBase));
  1356. BABYLON.PointerInfo = PointerInfo;
  1357. })(BABYLON || (BABYLON = {}));
  1358. //# sourceMappingURL=babylon.pointerEvents.js.map
  1359. var BABYLON;
  1360. (function (BABYLON) {
  1361. BABYLON.ToGammaSpace = 1 / 2.2;
  1362. BABYLON.ToLinearSpace = 2.2;
  1363. BABYLON.Epsilon = 0.001;
  1364. /**
  1365. * Class used to hold a RBG color
  1366. */
  1367. var Color3 = /** @class */ (function () {
  1368. /**
  1369. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1370. * @param r defines the red component (between 0 and 1, default is 0)
  1371. * @param g defines the green component (between 0 and 1, default is 0)
  1372. * @param b defines the blue component (between 0 and 1, default is 0)
  1373. */
  1374. function Color3(
  1375. /**
  1376. * Defines the red component (between 0 and 1, default is 0)
  1377. */
  1378. r,
  1379. /**
  1380. * Defines the green component (between 0 and 1, default is 0)
  1381. */
  1382. g,
  1383. /**
  1384. * Defines the blue component (between 0 and 1, default is 0)
  1385. */
  1386. b) {
  1387. if (r === void 0) { r = 0; }
  1388. if (g === void 0) { g = 0; }
  1389. if (b === void 0) { b = 0; }
  1390. this.r = r;
  1391. this.g = g;
  1392. this.b = b;
  1393. }
  1394. /**
  1395. * Creates a string with the Color3 current values
  1396. * @returns the string representation of the Color3 object
  1397. */
  1398. Color3.prototype.toString = function () {
  1399. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1400. };
  1401. /**
  1402. * Returns the string "Color3"
  1403. * @returns "Color3"
  1404. */
  1405. Color3.prototype.getClassName = function () {
  1406. return "Color3";
  1407. };
  1408. /**
  1409. * Compute the Color3 hash code
  1410. * @returns an unique number that can be used to hash Color3 objects
  1411. */
  1412. Color3.prototype.getHashCode = function () {
  1413. var hash = this.r || 0;
  1414. hash = (hash * 397) ^ (this.g || 0);
  1415. hash = (hash * 397) ^ (this.b || 0);
  1416. return hash;
  1417. };
  1418. // Operators
  1419. /**
  1420. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1421. * @param array defines the array where to store the r,g,b components
  1422. * @param index defines an optional index in the target array to define where to start storing values
  1423. * @returns the current Color3 object
  1424. */
  1425. Color3.prototype.toArray = function (array, index) {
  1426. if (index === undefined) {
  1427. index = 0;
  1428. }
  1429. array[index] = this.r;
  1430. array[index + 1] = this.g;
  1431. array[index + 2] = this.b;
  1432. return this;
  1433. };
  1434. /**
  1435. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1436. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1437. * @returns a new {BABYLON.Color4} object
  1438. */
  1439. Color3.prototype.toColor4 = function (alpha) {
  1440. if (alpha === void 0) { alpha = 1; }
  1441. return new Color4(this.r, this.g, this.b, alpha);
  1442. };
  1443. /**
  1444. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1445. * @returns the new array
  1446. */
  1447. Color3.prototype.asArray = function () {
  1448. var result = new Array();
  1449. this.toArray(result, 0);
  1450. return result;
  1451. };
  1452. /**
  1453. * Returns the luminance value
  1454. * @returns a float value
  1455. */
  1456. Color3.prototype.toLuminance = function () {
  1457. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1458. };
  1459. /**
  1460. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1461. * @param otherColor defines the second operand
  1462. * @returns the new Color3 object
  1463. */
  1464. Color3.prototype.multiply = function (otherColor) {
  1465. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1466. };
  1467. /**
  1468. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1469. * @param otherColor defines the second operand
  1470. * @param result defines the Color3 object where to store the result
  1471. * @returns the current Color3
  1472. */
  1473. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1474. result.r = this.r * otherColor.r;
  1475. result.g = this.g * otherColor.g;
  1476. result.b = this.b * otherColor.b;
  1477. return this;
  1478. };
  1479. /**
  1480. * Determines equality between Color3 objects
  1481. * @param otherColor defines the second operand
  1482. * @returns true if the rgb values are equal to the passed ones
  1483. */
  1484. Color3.prototype.equals = function (otherColor) {
  1485. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1486. };
  1487. /**
  1488. * Determines equality between the current Color3 object and a set of r,b,g values
  1489. * @param r defines the red component to check
  1490. * @param g defines the green component to check
  1491. * @param b defines the blue component to check
  1492. * @returns true if the rgb values are equal to the passed ones
  1493. */
  1494. Color3.prototype.equalsFloats = function (r, g, b) {
  1495. return this.r === r && this.g === g && this.b === b;
  1496. };
  1497. /**
  1498. * Multiplies in place each rgb value by scale
  1499. * @param scale defines the scaling factor
  1500. * @returns the updated Color3.
  1501. */
  1502. Color3.prototype.scale = function (scale) {
  1503. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1504. };
  1505. /**
  1506. * Multiplies the rgb values by scale and stores the result into "result"
  1507. * @param scale defines the scaling factor
  1508. * @param result defines the Color3 object where to store the result
  1509. * @returns the unmodified current Color3.
  1510. */
  1511. Color3.prototype.scaleToRef = function (scale, result) {
  1512. result.r = this.r * scale;
  1513. result.g = this.g * scale;
  1514. result.b = this.b * scale;
  1515. return this;
  1516. };
  1517. /**
  1518. * Clamps the rgb values by the min and max values and stores the result into "result"
  1519. * @param min defines minimum clamping value (default is 0)
  1520. * @param max defines maximum clamping value (default is 1)
  1521. * @param result defines color to store the result into
  1522. * @returns the original Color3
  1523. */
  1524. Color3.prototype.clampToRef = function (min, max, result) {
  1525. if (min === void 0) { min = 0; }
  1526. if (max === void 0) { max = 1; }
  1527. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1528. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1529. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1530. return this;
  1531. };
  1532. /**
  1533. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1534. * @param otherColor defines the second operand
  1535. * @returns the new Color3
  1536. */
  1537. Color3.prototype.add = function (otherColor) {
  1538. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1539. };
  1540. /**
  1541. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1542. * @param otherColor defines the second operand
  1543. * @param result defines Color3 object to store the result into
  1544. * @returns the unmodified current Color3
  1545. */
  1546. Color3.prototype.addToRef = function (otherColor, result) {
  1547. result.r = this.r + otherColor.r;
  1548. result.g = this.g + otherColor.g;
  1549. result.b = this.b + otherColor.b;
  1550. return this;
  1551. };
  1552. /**
  1553. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1554. * @param otherColor defines the second operand
  1555. * @returns the new Color3
  1556. */
  1557. Color3.prototype.subtract = function (otherColor) {
  1558. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1559. };
  1560. /**
  1561. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1562. * @param otherColor defines the second operand
  1563. * @param result defines Color3 object to store the result into
  1564. * @returns the unmodified current Color3
  1565. */
  1566. Color3.prototype.subtractToRef = function (otherColor, result) {
  1567. result.r = this.r - otherColor.r;
  1568. result.g = this.g - otherColor.g;
  1569. result.b = this.b - otherColor.b;
  1570. return this;
  1571. };
  1572. /**
  1573. * Copy the current object
  1574. * @returns a new Color3 copied the current one
  1575. */
  1576. Color3.prototype.clone = function () {
  1577. return new Color3(this.r, this.g, this.b);
  1578. };
  1579. /**
  1580. * Copies the rgb values from the source in the current Color3
  1581. * @param source defines the source Color3 object
  1582. * @returns the updated Color3 object
  1583. */
  1584. Color3.prototype.copyFrom = function (source) {
  1585. this.r = source.r;
  1586. this.g = source.g;
  1587. this.b = source.b;
  1588. return this;
  1589. };
  1590. /**
  1591. * Updates the Color3 rgb values from the passed floats
  1592. * @param r defines the red component to read from
  1593. * @param g defines the green component to read from
  1594. * @param b defines the blue component to read from
  1595. * @returns the current Color3 object
  1596. */
  1597. Color3.prototype.copyFromFloats = function (r, g, b) {
  1598. this.r = r;
  1599. this.g = g;
  1600. this.b = b;
  1601. return this;
  1602. };
  1603. /**
  1604. * Updates the Color3 rgb values from the passed floats
  1605. * @param r defines the red component to read from
  1606. * @param g defines the green component to read from
  1607. * @param b defines the blue component to read from
  1608. * @returns the current Color3 object
  1609. */
  1610. Color3.prototype.set = function (r, g, b) {
  1611. return this.copyFromFloats(r, g, b);
  1612. };
  1613. /**
  1614. * Compute the Color3 hexadecimal code as a string
  1615. * @returns a string containing the hexadecimal representation of the Color3 object
  1616. */
  1617. Color3.prototype.toHexString = function () {
  1618. var intR = (this.r * 255) | 0;
  1619. var intG = (this.g * 255) | 0;
  1620. var intB = (this.b * 255) | 0;
  1621. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1622. };
  1623. /**
  1624. * Computes a new Color3 converted from the current one to linear space
  1625. * @returns a new Color3 object
  1626. */
  1627. Color3.prototype.toLinearSpace = function () {
  1628. var convertedColor = new Color3();
  1629. this.toLinearSpaceToRef(convertedColor);
  1630. return convertedColor;
  1631. };
  1632. /**
  1633. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1634. * @param convertedColor defines the Color3 object where to store the linear space version
  1635. * @returns the unmodified Color3
  1636. */
  1637. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1638. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1639. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1640. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1641. return this;
  1642. };
  1643. /**
  1644. * Computes a new Color3 converted from the current one to gamma space
  1645. * @returns a new Color3 object
  1646. */
  1647. Color3.prototype.toGammaSpace = function () {
  1648. var convertedColor = new Color3();
  1649. this.toGammaSpaceToRef(convertedColor);
  1650. return convertedColor;
  1651. };
  1652. /**
  1653. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1654. * @param convertedColor defines the Color3 object where to store the gamma space version
  1655. * @returns the unmodified Color3
  1656. */
  1657. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1658. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1659. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1660. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1661. return this;
  1662. };
  1663. // Statics
  1664. /**
  1665. * Creates a new Color3 from the string containing valid hexadecimal values
  1666. * @param hex defines a string containing valid hexadecimal values
  1667. * @returns a new Color3 object
  1668. */
  1669. Color3.FromHexString = function (hex) {
  1670. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1671. return new Color3(0, 0, 0);
  1672. }
  1673. var r = parseInt(hex.substring(1, 3), 16);
  1674. var g = parseInt(hex.substring(3, 5), 16);
  1675. var b = parseInt(hex.substring(5, 7), 16);
  1676. return Color3.FromInts(r, g, b);
  1677. };
  1678. /**
  1679. * Creates a new Vector3 from the starting index of the passed array
  1680. * @param array defines the source array
  1681. * @param offset defines an offset in the source array
  1682. * @returns a new Color3 object
  1683. */
  1684. Color3.FromArray = function (array, offset) {
  1685. if (offset === void 0) { offset = 0; }
  1686. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1687. };
  1688. /**
  1689. * Creates a new Color3 from integer values (< 256)
  1690. * @param r defines the red component to read from (value between 0 and 255)
  1691. * @param g defines the green component to read from (value between 0 and 255)
  1692. * @param b defines the blue component to read from (value between 0 and 255)
  1693. * @returns a new Color3 object
  1694. */
  1695. Color3.FromInts = function (r, g, b) {
  1696. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1697. };
  1698. /**
  1699. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1700. * @param start defines the start Color3 value
  1701. * @param end defines the end Color3 value
  1702. * @param amount defines the gradient value between start and end
  1703. * @returns a new Color3 object
  1704. */
  1705. Color3.Lerp = function (start, end, amount) {
  1706. var r = start.r + ((end.r - start.r) * amount);
  1707. var g = start.g + ((end.g - start.g) * amount);
  1708. var b = start.b + ((end.b - start.b) * amount);
  1709. return new Color3(r, g, b);
  1710. };
  1711. /**
  1712. * Returns a Color3 value containing a red color
  1713. * @returns a new Color3 object
  1714. */
  1715. Color3.Red = function () { return new Color3(1, 0, 0); };
  1716. /**
  1717. * Returns a Color3 value containing a green color
  1718. * @returns a new Color3 object
  1719. */
  1720. Color3.Green = function () { return new Color3(0, 1, 0); };
  1721. /**
  1722. * Returns a Color3 value containing a blue color
  1723. * @returns a new Color3 object
  1724. */
  1725. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1726. /**
  1727. * Returns a Color3 value containing a black color
  1728. * @returns a new Color3 object
  1729. */
  1730. Color3.Black = function () { return new Color3(0, 0, 0); };
  1731. /**
  1732. * Returns a Color3 value containing a white color
  1733. * @returns a new Color3 object
  1734. */
  1735. Color3.White = function () { return new Color3(1, 1, 1); };
  1736. /**
  1737. * Returns a Color3 value containing a purple color
  1738. * @returns a new Color3 object
  1739. */
  1740. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1741. /**
  1742. * Returns a Color3 value containing a magenta color
  1743. * @returns a new Color3 object
  1744. */
  1745. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1746. /**
  1747. * Returns a Color3 value containing a yellow color
  1748. * @returns a new Color3 object
  1749. */
  1750. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1751. /**
  1752. * Returns a Color3 value containing a gray color
  1753. * @returns a new Color3 object
  1754. */
  1755. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1756. /**
  1757. * Returns a Color3 value containing a teal color
  1758. * @returns a new Color3 object
  1759. */
  1760. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1761. /**
  1762. * Returns a Color3 value containing a random color
  1763. * @returns a new Color3 object
  1764. */
  1765. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1766. return Color3;
  1767. }());
  1768. BABYLON.Color3 = Color3;
  1769. /**
  1770. * Class used to hold a RBGA color
  1771. */
  1772. var Color4 = /** @class */ (function () {
  1773. /**
  1774. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1775. * @param r defines the red component (between 0 and 1, default is 0)
  1776. * @param g defines the green component (between 0 and 1, default is 0)
  1777. * @param b defines the blue component (between 0 and 1, default is 0)
  1778. * @param a defines the alpha component (between 0 and 1, default is 1)
  1779. */
  1780. function Color4(
  1781. /**
  1782. * Defines the red component (between 0 and 1, default is 0)
  1783. */
  1784. r,
  1785. /**
  1786. * Defines the green component (between 0 and 1, default is 0)
  1787. */
  1788. g,
  1789. /**
  1790. * Defines the blue component (between 0 and 1, default is 0)
  1791. */
  1792. b,
  1793. /**
  1794. * Defines the alpha component (between 0 and 1, default is 1)
  1795. */
  1796. a) {
  1797. if (r === void 0) { r = 0; }
  1798. if (g === void 0) { g = 0; }
  1799. if (b === void 0) { b = 0; }
  1800. if (a === void 0) { a = 1; }
  1801. this.r = r;
  1802. this.g = g;
  1803. this.b = b;
  1804. this.a = a;
  1805. }
  1806. // Operators
  1807. /**
  1808. * Adds in place the passed Color4 values to the current Color4 object
  1809. * @param right defines the second operand
  1810. * @returns the current updated Color4 object
  1811. */
  1812. Color4.prototype.addInPlace = function (right) {
  1813. this.r += right.r;
  1814. this.g += right.g;
  1815. this.b += right.b;
  1816. this.a += right.a;
  1817. return this;
  1818. };
  1819. /**
  1820. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1821. * @returns the new array
  1822. */
  1823. Color4.prototype.asArray = function () {
  1824. var result = new Array();
  1825. this.toArray(result, 0);
  1826. return result;
  1827. };
  1828. /**
  1829. * Stores from the starting index in the passed array the Color4 successive values
  1830. * @param array defines the array where to store the r,g,b components
  1831. * @param index defines an optional index in the target array to define where to start storing values
  1832. * @returns the current Color4 object
  1833. */
  1834. Color4.prototype.toArray = function (array, index) {
  1835. if (index === undefined) {
  1836. index = 0;
  1837. }
  1838. array[index] = this.r;
  1839. array[index + 1] = this.g;
  1840. array[index + 2] = this.b;
  1841. array[index + 3] = this.a;
  1842. return this;
  1843. };
  1844. /**
  1845. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1846. * @param right defines the second operand
  1847. * @returns a new Color4 object
  1848. */
  1849. Color4.prototype.add = function (right) {
  1850. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1851. };
  1852. /**
  1853. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1854. * @param right defines the second operand
  1855. * @returns a new Color4 object
  1856. */
  1857. Color4.prototype.subtract = function (right) {
  1858. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1859. };
  1860. /**
  1861. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1862. * @param right defines the second operand
  1863. * @param result defines the Color4 object where to store the result
  1864. * @returns the current Color4 object
  1865. */
  1866. Color4.prototype.subtractToRef = function (right, result) {
  1867. result.r = this.r - right.r;
  1868. result.g = this.g - right.g;
  1869. result.b = this.b - right.b;
  1870. result.a = this.a - right.a;
  1871. return this;
  1872. };
  1873. /**
  1874. * Creates a new Color4 with the current Color4 values multiplied by scale
  1875. * @param scale defines the scaling factor to apply
  1876. * @returns a new Color4 object
  1877. */
  1878. Color4.prototype.scale = function (scale) {
  1879. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1880. };
  1881. /**
  1882. * Multiplies the current Color4 values by scale and stores the result in "result"
  1883. * @param scale defines the scaling factor to apply
  1884. * @param result defines the Color4 object where to store the result
  1885. * @returns the current Color4.
  1886. */
  1887. Color4.prototype.scaleToRef = function (scale, result) {
  1888. result.r = this.r * scale;
  1889. result.g = this.g * scale;
  1890. result.b = this.b * scale;
  1891. result.a = this.a * scale;
  1892. return this;
  1893. };
  1894. /**
  1895. * Clamps the rgb values by the min and max values and stores the result into "result"
  1896. * @param min defines minimum clamping value (default is 0)
  1897. * @param max defines maximum clamping value (default is 1)
  1898. * @param result defines color to store the result into.
  1899. * @returns the cuurent Color4
  1900. */
  1901. Color4.prototype.clampToRef = function (min, max, result) {
  1902. if (min === void 0) { min = 0; }
  1903. if (max === void 0) { max = 1; }
  1904. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1905. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1906. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1907. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1908. return this;
  1909. };
  1910. /**
  1911. * Multipy an Color4 value by another and return a new Color4 object
  1912. * @param color defines the Color4 value to multiply by
  1913. * @returns a new Color4 object
  1914. */
  1915. Color4.prototype.multiply = function (color) {
  1916. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1917. };
  1918. /**
  1919. * Multipy a Color4 value by another and push the result in a reference value
  1920. * @param color defines the Color4 value to multiply by
  1921. * @param result defines the Color4 to fill the result in
  1922. * @returns the result Color4
  1923. */
  1924. Color4.prototype.multiplyToRef = function (color, result) {
  1925. result.r = this.r * color.r;
  1926. result.g = this.g * color.g;
  1927. result.b = this.b * color.b;
  1928. result.a = this.a * color.a;
  1929. return result;
  1930. };
  1931. /**
  1932. * Creates a string with the Color4 current values
  1933. * @returns the string representation of the Color4 object
  1934. */
  1935. Color4.prototype.toString = function () {
  1936. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1937. };
  1938. /**
  1939. * Returns the string "Color4"
  1940. * @returns "Color4"
  1941. */
  1942. Color4.prototype.getClassName = function () {
  1943. return "Color4";
  1944. };
  1945. /**
  1946. * Compute the Color4 hash code
  1947. * @returns an unique number that can be used to hash Color4 objects
  1948. */
  1949. Color4.prototype.getHashCode = function () {
  1950. var hash = this.r || 0;
  1951. hash = (hash * 397) ^ (this.g || 0);
  1952. hash = (hash * 397) ^ (this.b || 0);
  1953. hash = (hash * 397) ^ (this.a || 0);
  1954. return hash;
  1955. };
  1956. /**
  1957. * Creates a new Color4 copied from the current one
  1958. * @returns a new Color4 object
  1959. */
  1960. Color4.prototype.clone = function () {
  1961. return new Color4(this.r, this.g, this.b, this.a);
  1962. };
  1963. /**
  1964. * Copies the passed Color4 values into the current one
  1965. * @param source defines the source Color4 object
  1966. * @returns the current updated Color4 object
  1967. */
  1968. Color4.prototype.copyFrom = function (source) {
  1969. this.r = source.r;
  1970. this.g = source.g;
  1971. this.b = source.b;
  1972. this.a = source.a;
  1973. return this;
  1974. };
  1975. /**
  1976. * Copies the passed float values into the current one
  1977. * @param r defines the red component to read from
  1978. * @param g defines the green component to read from
  1979. * @param b defines the blue component to read from
  1980. * @param a defines the alpha component to read from
  1981. * @returns the current updated Color4 object
  1982. */
  1983. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1984. this.r = r;
  1985. this.g = g;
  1986. this.b = b;
  1987. this.a = a;
  1988. return this;
  1989. };
  1990. /**
  1991. * Copies the passed float values into the current one
  1992. * @param r defines the red component to read from
  1993. * @param g defines the green component to read from
  1994. * @param b defines the blue component to read from
  1995. * @param a defines the alpha component to read from
  1996. * @returns the current updated Color4 object
  1997. */
  1998. Color4.prototype.set = function (r, g, b, a) {
  1999. return this.copyFromFloats(r, g, b, a);
  2000. };
  2001. /**
  2002. * Compute the Color4 hexadecimal code as a string
  2003. * @returns a string containing the hexadecimal representation of the Color4 object
  2004. */
  2005. Color4.prototype.toHexString = function () {
  2006. var intR = (this.r * 255) | 0;
  2007. var intG = (this.g * 255) | 0;
  2008. var intB = (this.b * 255) | 0;
  2009. var intA = (this.a * 255) | 0;
  2010. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2011. };
  2012. /**
  2013. * Computes a new Color4 converted from the current one to linear space
  2014. * @returns a new Color4 object
  2015. */
  2016. Color4.prototype.toLinearSpace = function () {
  2017. var convertedColor = new Color4();
  2018. this.toLinearSpaceToRef(convertedColor);
  2019. return convertedColor;
  2020. };
  2021. /**
  2022. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2023. * @param convertedColor defines the Color4 object where to store the linear space version
  2024. * @returns the unmodified Color4
  2025. */
  2026. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2027. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2028. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2029. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2030. convertedColor.a = this.a;
  2031. return this;
  2032. };
  2033. /**
  2034. * Computes a new Color4 converted from the current one to gamma space
  2035. * @returns a new Color4 object
  2036. */
  2037. Color4.prototype.toGammaSpace = function () {
  2038. var convertedColor = new Color4();
  2039. this.toGammaSpaceToRef(convertedColor);
  2040. return convertedColor;
  2041. };
  2042. /**
  2043. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2044. * @param convertedColor defines the Color4 object where to store the gamma space version
  2045. * @returns the unmodified Color4
  2046. */
  2047. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2048. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2049. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2050. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2051. convertedColor.a = this.a;
  2052. return this;
  2053. };
  2054. // Statics
  2055. /**
  2056. * Creates a new Color4 from the string containing valid hexadecimal values
  2057. * @param hex defines a string containing valid hexadecimal values
  2058. * @returns a new Color4 object
  2059. */
  2060. Color4.FromHexString = function (hex) {
  2061. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2062. return new Color4(0.0, 0.0, 0.0, 0.0);
  2063. }
  2064. var r = parseInt(hex.substring(1, 3), 16);
  2065. var g = parseInt(hex.substring(3, 5), 16);
  2066. var b = parseInt(hex.substring(5, 7), 16);
  2067. var a = parseInt(hex.substring(7, 9), 16);
  2068. return Color4.FromInts(r, g, b, a);
  2069. };
  2070. /**
  2071. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2072. * @param left defines the start value
  2073. * @param right defines the end value
  2074. * @param amount defines the gradient factor
  2075. * @returns a new Color4 object
  2076. */
  2077. Color4.Lerp = function (left, right, amount) {
  2078. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2079. Color4.LerpToRef(left, right, amount, result);
  2080. return result;
  2081. };
  2082. /**
  2083. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2084. * @param left defines the start value
  2085. * @param right defines the end value
  2086. * @param amount defines the gradient factor
  2087. * @param result defines the Color4 object where to store data
  2088. */
  2089. Color4.LerpToRef = function (left, right, amount, result) {
  2090. result.r = left.r + (right.r - left.r) * amount;
  2091. result.g = left.g + (right.g - left.g) * amount;
  2092. result.b = left.b + (right.b - left.b) * amount;
  2093. result.a = left.a + (right.a - left.a) * amount;
  2094. };
  2095. /**
  2096. * Creates a new Color4 from the starting index element of the passed array
  2097. * @param array defines the source array to read from
  2098. * @param offset defines the offset in the source array
  2099. * @returns a new Color4 object
  2100. */
  2101. Color4.FromArray = function (array, offset) {
  2102. if (offset === void 0) { offset = 0; }
  2103. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2104. };
  2105. /**
  2106. * Creates a new Color3 from integer values (< 256)
  2107. * @param r defines the red component to read from (value between 0 and 255)
  2108. * @param g defines the green component to read from (value between 0 and 255)
  2109. * @param b defines the blue component to read from (value between 0 and 255)
  2110. * @param a defines the alpha component to read from (value between 0 and 255)
  2111. * @returns a new Color3 object
  2112. */
  2113. Color4.FromInts = function (r, g, b, a) {
  2114. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2115. };
  2116. /**
  2117. * Check the content of a given array and convert it to an array containing RGBA data
  2118. * If the original array was already containing count * 4 values then it is returned directly
  2119. * @param colors defines the array to check
  2120. * @param count defines the number of RGBA data to expect
  2121. * @returns an array containing count * 4 values (RGBA)
  2122. */
  2123. Color4.CheckColors4 = function (colors, count) {
  2124. // Check if color3 was used
  2125. if (colors.length === count * 3) {
  2126. var colors4 = [];
  2127. for (var index = 0; index < colors.length; index += 3) {
  2128. var newIndex = (index / 3) * 4;
  2129. colors4[newIndex] = colors[index];
  2130. colors4[newIndex + 1] = colors[index + 1];
  2131. colors4[newIndex + 2] = colors[index + 2];
  2132. colors4[newIndex + 3] = 1.0;
  2133. }
  2134. return colors4;
  2135. }
  2136. return colors;
  2137. };
  2138. return Color4;
  2139. }());
  2140. BABYLON.Color4 = Color4;
  2141. var Vector2 = /** @class */ (function () {
  2142. /**
  2143. * Creates a new Vector2 from the passed x and y coordinates.
  2144. */
  2145. function Vector2(x, y) {
  2146. this.x = x;
  2147. this.y = y;
  2148. }
  2149. /**
  2150. * Returns a string with the Vector2 coordinates.
  2151. */
  2152. Vector2.prototype.toString = function () {
  2153. return "{X: " + this.x + " Y:" + this.y + "}";
  2154. };
  2155. /**
  2156. * Returns the string "Vector2"
  2157. */
  2158. Vector2.prototype.getClassName = function () {
  2159. return "Vector2";
  2160. };
  2161. /**
  2162. * Returns the Vector2 hash code as a number.
  2163. */
  2164. Vector2.prototype.getHashCode = function () {
  2165. var hash = this.x || 0;
  2166. hash = (hash * 397) ^ (this.y || 0);
  2167. return hash;
  2168. };
  2169. // Operators
  2170. /**
  2171. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2172. * Returns the Vector2.
  2173. */
  2174. Vector2.prototype.toArray = function (array, index) {
  2175. if (index === void 0) { index = 0; }
  2176. array[index] = this.x;
  2177. array[index + 1] = this.y;
  2178. return this;
  2179. };
  2180. /**
  2181. * Returns a new array with 2 elements : the Vector2 coordinates.
  2182. */
  2183. Vector2.prototype.asArray = function () {
  2184. var result = new Array();
  2185. this.toArray(result, 0);
  2186. return result;
  2187. };
  2188. /**
  2189. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2190. * Returns the updated Vector2.
  2191. */
  2192. Vector2.prototype.copyFrom = function (source) {
  2193. this.x = source.x;
  2194. this.y = source.y;
  2195. return this;
  2196. };
  2197. /**
  2198. * Sets the Vector2 coordinates with the passed floats.
  2199. * Returns the updated Vector2.
  2200. */
  2201. Vector2.prototype.copyFromFloats = function (x, y) {
  2202. this.x = x;
  2203. this.y = y;
  2204. return this;
  2205. };
  2206. /**
  2207. * Sets the Vector2 coordinates with the passed floats.
  2208. * Returns the updated Vector2.
  2209. */
  2210. Vector2.prototype.set = function (x, y) {
  2211. return this.copyFromFloats(x, y);
  2212. };
  2213. /**
  2214. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2215. */
  2216. Vector2.prototype.add = function (otherVector) {
  2217. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2218. };
  2219. /**
  2220. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2221. * Returns the Vector2.
  2222. */
  2223. Vector2.prototype.addToRef = function (otherVector, result) {
  2224. result.x = this.x + otherVector.x;
  2225. result.y = this.y + otherVector.y;
  2226. return this;
  2227. };
  2228. /**
  2229. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2230. * Returns the updated Vector2.
  2231. */
  2232. Vector2.prototype.addInPlace = function (otherVector) {
  2233. this.x += otherVector.x;
  2234. this.y += otherVector.y;
  2235. return this;
  2236. };
  2237. /**
  2238. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2239. */
  2240. Vector2.prototype.addVector3 = function (otherVector) {
  2241. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2242. };
  2243. /**
  2244. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2245. */
  2246. Vector2.prototype.subtract = function (otherVector) {
  2247. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2248. };
  2249. /**
  2250. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2251. * Returns the Vector2.
  2252. */
  2253. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2254. result.x = this.x - otherVector.x;
  2255. result.y = this.y - otherVector.y;
  2256. return this;
  2257. };
  2258. /**
  2259. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2260. * Returns the updated Vector2.
  2261. */
  2262. Vector2.prototype.subtractInPlace = function (otherVector) {
  2263. this.x -= otherVector.x;
  2264. this.y -= otherVector.y;
  2265. return this;
  2266. };
  2267. /**
  2268. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2269. * Returns the updated Vector2.
  2270. */
  2271. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2272. this.x *= otherVector.x;
  2273. this.y *= otherVector.y;
  2274. return this;
  2275. };
  2276. /**
  2277. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2278. */
  2279. Vector2.prototype.multiply = function (otherVector) {
  2280. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2281. };
  2282. /**
  2283. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2284. * Returns the Vector2.
  2285. */
  2286. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2287. result.x = this.x * otherVector.x;
  2288. result.y = this.y * otherVector.y;
  2289. return this;
  2290. };
  2291. /**
  2292. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2293. */
  2294. Vector2.prototype.multiplyByFloats = function (x, y) {
  2295. return new Vector2(this.x * x, this.y * y);
  2296. };
  2297. /**
  2298. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2299. */
  2300. Vector2.prototype.divide = function (otherVector) {
  2301. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2302. };
  2303. /**
  2304. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2305. * Returns the Vector2.
  2306. */
  2307. Vector2.prototype.divideToRef = function (otherVector, result) {
  2308. result.x = this.x / otherVector.x;
  2309. result.y = this.y / otherVector.y;
  2310. return this;
  2311. };
  2312. /**
  2313. * Divides the current Vector3 coordinates by the passed ones.
  2314. * Returns the updated Vector3.
  2315. */
  2316. Vector2.prototype.divideInPlace = function (otherVector) {
  2317. return this.divideToRef(otherVector, this);
  2318. };
  2319. /**
  2320. * Returns a new Vector2 with current Vector2 negated coordinates.
  2321. */
  2322. Vector2.prototype.negate = function () {
  2323. return new Vector2(-this.x, -this.y);
  2324. };
  2325. /**
  2326. * Multiply the Vector2 coordinates by scale.
  2327. * Returns the updated Vector2.
  2328. */
  2329. Vector2.prototype.scaleInPlace = function (scale) {
  2330. this.x *= scale;
  2331. this.y *= scale;
  2332. return this;
  2333. };
  2334. /**
  2335. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2336. */
  2337. Vector2.prototype.scale = function (scale) {
  2338. return new Vector2(this.x * scale, this.y * scale);
  2339. };
  2340. /**
  2341. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2342. */
  2343. Vector2.prototype.equals = function (otherVector) {
  2344. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2345. };
  2346. /**
  2347. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2348. */
  2349. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2350. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2351. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2352. };
  2353. // Properties
  2354. /**
  2355. * Returns the vector length (float).
  2356. */
  2357. Vector2.prototype.length = function () {
  2358. return Math.sqrt(this.x * this.x + this.y * this.y);
  2359. };
  2360. /**
  2361. * Returns the vector squared length (float);
  2362. */
  2363. Vector2.prototype.lengthSquared = function () {
  2364. return (this.x * this.x + this.y * this.y);
  2365. };
  2366. // Methods
  2367. /**
  2368. * Normalize the vector.
  2369. * Returns the updated Vector2.
  2370. */
  2371. Vector2.prototype.normalize = function () {
  2372. var len = this.length();
  2373. if (len === 0)
  2374. return this;
  2375. var num = 1.0 / len;
  2376. this.x *= num;
  2377. this.y *= num;
  2378. return this;
  2379. };
  2380. /**
  2381. * Returns a new Vector2 copied from the Vector2.
  2382. */
  2383. Vector2.prototype.clone = function () {
  2384. return new Vector2(this.x, this.y);
  2385. };
  2386. // Statics
  2387. /**
  2388. * Returns a new Vector2(0, 0)
  2389. */
  2390. Vector2.Zero = function () {
  2391. return new Vector2(0, 0);
  2392. };
  2393. /**
  2394. * Returns a new Vector2(1, 1)
  2395. */
  2396. Vector2.One = function () {
  2397. return new Vector2(1, 1);
  2398. };
  2399. /**
  2400. * Returns a new Vector2 set from the passed index element of the passed array.
  2401. */
  2402. Vector2.FromArray = function (array, offset) {
  2403. if (offset === void 0) { offset = 0; }
  2404. return new Vector2(array[offset], array[offset + 1]);
  2405. };
  2406. /**
  2407. * Sets "result" from the passed index element of the passed array.
  2408. */
  2409. Vector2.FromArrayToRef = function (array, offset, result) {
  2410. result.x = array[offset];
  2411. result.y = array[offset + 1];
  2412. };
  2413. /**
  2414. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2415. */
  2416. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2417. var squared = amount * amount;
  2418. var cubed = amount * squared;
  2419. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2420. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2421. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2422. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2423. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2424. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2425. return new Vector2(x, y);
  2426. };
  2427. /**
  2428. * 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".
  2429. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2430. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2431. */
  2432. Vector2.Clamp = function (value, min, max) {
  2433. var x = value.x;
  2434. x = (x > max.x) ? max.x : x;
  2435. x = (x < min.x) ? min.x : x;
  2436. var y = value.y;
  2437. y = (y > max.y) ? max.y : y;
  2438. y = (y < min.y) ? min.y : y;
  2439. return new Vector2(x, y);
  2440. };
  2441. /**
  2442. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2443. */
  2444. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2445. var squared = amount * amount;
  2446. var cubed = amount * squared;
  2447. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2448. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2449. var part3 = (cubed - (2.0 * squared)) + amount;
  2450. var part4 = cubed - squared;
  2451. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2452. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2453. return new Vector2(x, y);
  2454. };
  2455. /**
  2456. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2457. */
  2458. Vector2.Lerp = function (start, end, amount) {
  2459. var x = start.x + ((end.x - start.x) * amount);
  2460. var y = start.y + ((end.y - start.y) * amount);
  2461. return new Vector2(x, y);
  2462. };
  2463. /**
  2464. * Returns the dot product (float) of the vector "left" and the vector "right".
  2465. */
  2466. Vector2.Dot = function (left, right) {
  2467. return left.x * right.x + left.y * right.y;
  2468. };
  2469. /**
  2470. * Returns a new Vector2 equal to the normalized passed vector.
  2471. */
  2472. Vector2.Normalize = function (vector) {
  2473. var newVector = vector.clone();
  2474. newVector.normalize();
  2475. return newVector;
  2476. };
  2477. /**
  2478. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2479. */
  2480. Vector2.Minimize = function (left, right) {
  2481. var x = (left.x < right.x) ? left.x : right.x;
  2482. var y = (left.y < right.y) ? left.y : right.y;
  2483. return new Vector2(x, y);
  2484. };
  2485. /**
  2486. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2487. */
  2488. Vector2.Maximize = function (left, right) {
  2489. var x = (left.x > right.x) ? left.x : right.x;
  2490. var y = (left.y > right.y) ? left.y : right.y;
  2491. return new Vector2(x, y);
  2492. };
  2493. /**
  2494. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2495. */
  2496. Vector2.Transform = function (vector, transformation) {
  2497. var r = Vector2.Zero();
  2498. Vector2.TransformToRef(vector, transformation, r);
  2499. return r;
  2500. };
  2501. /**
  2502. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2503. */
  2504. Vector2.TransformToRef = function (vector, transformation, result) {
  2505. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2506. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2507. result.x = x;
  2508. result.y = y;
  2509. };
  2510. /**
  2511. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2512. */
  2513. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2514. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2515. var sign = a < 0 ? -1 : 1;
  2516. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2517. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2518. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2519. };
  2520. /**
  2521. * Returns the distance (float) between the vectors "value1" and "value2".
  2522. */
  2523. Vector2.Distance = function (value1, value2) {
  2524. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2525. };
  2526. /**
  2527. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2528. */
  2529. Vector2.DistanceSquared = function (value1, value2) {
  2530. var x = value1.x - value2.x;
  2531. var y = value1.y - value2.y;
  2532. return (x * x) + (y * y);
  2533. };
  2534. /**
  2535. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2536. */
  2537. Vector2.Center = function (value1, value2) {
  2538. var center = value1.add(value2);
  2539. center.scaleInPlace(0.5);
  2540. return center;
  2541. };
  2542. /**
  2543. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2544. */
  2545. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2546. var l2 = Vector2.DistanceSquared(segA, segB);
  2547. if (l2 === 0.0) {
  2548. return Vector2.Distance(p, segA);
  2549. }
  2550. var v = segB.subtract(segA);
  2551. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2552. var proj = segA.add(v.multiplyByFloats(t, t));
  2553. return Vector2.Distance(p, proj);
  2554. };
  2555. return Vector2;
  2556. }());
  2557. BABYLON.Vector2 = Vector2;
  2558. /**
  2559. * Classed used to store (x,y,z) vector representation
  2560. * A Vector3 is the main object used in 3D geometry
  2561. * It can represent etiher the coordinates of a point the space, either a direction
  2562. * Reminder: Babylon.js uses a left handed forward facing system
  2563. */
  2564. var Vector3 = /** @class */ (function () {
  2565. /**
  2566. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2567. * @param x defines the first coordinates (on X axis)
  2568. * @param y defines the second coordinates (on Y axis)
  2569. * @param z defines the third coordinates (on Z axis)
  2570. */
  2571. function Vector3(
  2572. /**
  2573. * Defines the first coordinates (on X axis)
  2574. */
  2575. x,
  2576. /**
  2577. * Defines the second coordinates (on Y axis)
  2578. */
  2579. y,
  2580. /**
  2581. * Defines the third coordinates (on Z axis)
  2582. */
  2583. z) {
  2584. this.x = x;
  2585. this.y = y;
  2586. this.z = z;
  2587. }
  2588. /**
  2589. * Creates a string representation of the Vector3
  2590. * @returns a string with the Vector3 coordinates.
  2591. */
  2592. Vector3.prototype.toString = function () {
  2593. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2594. };
  2595. /**
  2596. * Gets the class name
  2597. * @returns the string "Vector3"
  2598. */
  2599. Vector3.prototype.getClassName = function () {
  2600. return "Vector3";
  2601. };
  2602. /**
  2603. * Creates the Vector3 hash code
  2604. * @returns a number which tends to be unique between Vector3 instances
  2605. */
  2606. Vector3.prototype.getHashCode = function () {
  2607. var hash = this.x || 0;
  2608. hash = (hash * 397) ^ (this.y || 0);
  2609. hash = (hash * 397) ^ (this.z || 0);
  2610. return hash;
  2611. };
  2612. // Operators
  2613. /**
  2614. * Creates an array containing three elements : the coordinates of the Vector3
  2615. * @returns a new array of numbers
  2616. */
  2617. Vector3.prototype.asArray = function () {
  2618. var result = [];
  2619. this.toArray(result, 0);
  2620. return result;
  2621. };
  2622. /**
  2623. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2624. * @param array defines the destination array
  2625. * @param index defines the offset in the destination array
  2626. * @returns the current Vector3
  2627. */
  2628. Vector3.prototype.toArray = function (array, index) {
  2629. if (index === void 0) { index = 0; }
  2630. array[index] = this.x;
  2631. array[index + 1] = this.y;
  2632. array[index + 2] = this.z;
  2633. return this;
  2634. };
  2635. /**
  2636. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2637. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2638. */
  2639. Vector3.prototype.toQuaternion = function () {
  2640. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2641. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2642. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2643. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2644. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2645. var cosy = Math.cos(this.y * 0.5);
  2646. var siny = Math.sin(this.y * 0.5);
  2647. result.x = coszMinusx * siny;
  2648. result.y = -sinzMinusx * siny;
  2649. result.z = sinxPlusz * cosy;
  2650. result.w = cosxPlusz * cosy;
  2651. return result;
  2652. };
  2653. /**
  2654. * Adds the passed vector to the current Vector3
  2655. * @param otherVector defines the second operand
  2656. * @returns the current updated Vector3
  2657. */
  2658. Vector3.prototype.addInPlace = function (otherVector) {
  2659. this.x += otherVector.x;
  2660. this.y += otherVector.y;
  2661. this.z += otherVector.z;
  2662. return this;
  2663. };
  2664. /**
  2665. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2666. * @param otherVector defines the second operand
  2667. * @returns the resulting Vector3
  2668. */
  2669. Vector3.prototype.add = function (otherVector) {
  2670. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2671. };
  2672. /**
  2673. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2674. * @param otherVector defines the second operand
  2675. * @param result defines the Vector3 object where to store the result
  2676. * @returns the current Vector3
  2677. */
  2678. Vector3.prototype.addToRef = function (otherVector, result) {
  2679. result.x = this.x + otherVector.x;
  2680. result.y = this.y + otherVector.y;
  2681. result.z = this.z + otherVector.z;
  2682. return this;
  2683. };
  2684. /**
  2685. * Subtract the passed vector from the current Vector3
  2686. * @param otherVector defines the second operand
  2687. * @returns the current updated Vector3
  2688. */
  2689. Vector3.prototype.subtractInPlace = function (otherVector) {
  2690. this.x -= otherVector.x;
  2691. this.y -= otherVector.y;
  2692. this.z -= otherVector.z;
  2693. return this;
  2694. };
  2695. /**
  2696. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2697. * @param otherVector defines the second operand
  2698. * @returns the resulting Vector3
  2699. */
  2700. Vector3.prototype.subtract = function (otherVector) {
  2701. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2702. };
  2703. /**
  2704. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2705. * @param otherVector defines the second operand
  2706. * @param result defines the Vector3 object where to store the result
  2707. * @returns the current Vector3
  2708. */
  2709. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2710. result.x = this.x - otherVector.x;
  2711. result.y = this.y - otherVector.y;
  2712. result.z = this.z - otherVector.z;
  2713. return this;
  2714. };
  2715. /**
  2716. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2717. * @param x defines the x coordinate of the operand
  2718. * @param y defines the y coordinate of the operand
  2719. * @param z defines the z coordinate of the operand
  2720. * @returns the resulting Vector3
  2721. */
  2722. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2723. return new Vector3(this.x - x, this.y - y, this.z - z);
  2724. };
  2725. /**
  2726. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2727. * @param x defines the x coordinate of the operand
  2728. * @param y defines the y coordinate of the operand
  2729. * @param z defines the z coordinate of the operand
  2730. * @param result defines the Vector3 object where to store the result
  2731. * @returns the current Vector3
  2732. */
  2733. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2734. result.x = this.x - x;
  2735. result.y = this.y - y;
  2736. result.z = this.z - z;
  2737. return this;
  2738. };
  2739. /**
  2740. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2741. * @returns a new Vector3
  2742. */
  2743. Vector3.prototype.negate = function () {
  2744. return new Vector3(-this.x, -this.y, -this.z);
  2745. };
  2746. /**
  2747. * Multiplies the Vector3 coordinates by the float "scale"
  2748. * @param scale defines the multiplier factor
  2749. * @returns the current updated Vector3
  2750. */
  2751. Vector3.prototype.scaleInPlace = function (scale) {
  2752. this.x *= scale;
  2753. this.y *= scale;
  2754. this.z *= scale;
  2755. return this;
  2756. };
  2757. /**
  2758. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2759. * @param scale defines the multiplier factor
  2760. * @returns a new Vector3
  2761. */
  2762. Vector3.prototype.scale = function (scale) {
  2763. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2764. };
  2765. /**
  2766. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2767. * @param scale defines the multiplier factor
  2768. * @param result defines the Vector3 object where to store the result
  2769. * @returns the current Vector3
  2770. */
  2771. Vector3.prototype.scaleToRef = function (scale, result) {
  2772. result.x = this.x * scale;
  2773. result.y = this.y * scale;
  2774. result.z = this.z * scale;
  2775. return this;
  2776. };
  2777. /**
  2778. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2779. * @param otherVector defines the second operand
  2780. * @returns true if both vectors are equals
  2781. */
  2782. Vector3.prototype.equals = function (otherVector) {
  2783. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2784. };
  2785. /**
  2786. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2787. * @param otherVector defines the second operand
  2788. * @param epsilon defines the minimal distance to define values as equals
  2789. * @returns true if both vectors are distant less than epsilon
  2790. */
  2791. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2792. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2793. 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);
  2794. };
  2795. /**
  2796. * Returns true if the current Vector3 coordinates equals the passed floats
  2797. * @param x defines the x coordinate of the operand
  2798. * @param y defines the y coordinate of the operand
  2799. * @param z defines the z coordinate of the operand
  2800. * @returns true if both vectors are equals
  2801. */
  2802. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2803. return this.x === x && this.y === y && this.z === z;
  2804. };
  2805. /**
  2806. * Multiplies the current Vector3 coordinates by the passed ones
  2807. * @param otherVector defines the second operand
  2808. * @returns the current updated Vector3
  2809. */
  2810. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2811. this.x *= otherVector.x;
  2812. this.y *= otherVector.y;
  2813. this.z *= otherVector.z;
  2814. return this;
  2815. };
  2816. /**
  2817. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2818. * @param otherVector defines the second operand
  2819. * @returns the new Vector3
  2820. */
  2821. Vector3.prototype.multiply = function (otherVector) {
  2822. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2823. };
  2824. /**
  2825. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2826. * @param otherVector defines the second operand
  2827. * @param result defines the Vector3 object where to store the result
  2828. * @returns the current Vector3
  2829. */
  2830. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2831. result.x = this.x * otherVector.x;
  2832. result.y = this.y * otherVector.y;
  2833. result.z = this.z * otherVector.z;
  2834. return this;
  2835. };
  2836. /**
  2837. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2838. * @param x defines the x coordinate of the operand
  2839. * @param y defines the y coordinate of the operand
  2840. * @param z defines the z coordinate of the operand
  2841. * @returns the new Vector3
  2842. */
  2843. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2844. return new Vector3(this.x * x, this.y * y, this.z * z);
  2845. };
  2846. /**
  2847. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2848. * @param otherVector defines the second operand
  2849. * @returns the new Vector3
  2850. */
  2851. Vector3.prototype.divide = function (otherVector) {
  2852. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2853. };
  2854. /**
  2855. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2856. * @param otherVector defines the second operand
  2857. * @param result defines the Vector3 object where to store the result
  2858. * @returns the current Vector3
  2859. */
  2860. Vector3.prototype.divideToRef = function (otherVector, result) {
  2861. result.x = this.x / otherVector.x;
  2862. result.y = this.y / otherVector.y;
  2863. result.z = this.z / otherVector.z;
  2864. return this;
  2865. };
  2866. /**
  2867. * Divides the current Vector3 coordinates by the passed ones.
  2868. * @param otherVector defines the second operand
  2869. * @returns the current updated Vector3
  2870. */
  2871. Vector3.prototype.divideInPlace = function (otherVector) {
  2872. return this.divideToRef(otherVector, this);
  2873. };
  2874. /**
  2875. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2876. * @param other defines the second operand
  2877. * @returns the current updated Vector3
  2878. */
  2879. Vector3.prototype.minimizeInPlace = function (other) {
  2880. if (other.x < this.x)
  2881. this.x = other.x;
  2882. if (other.y < this.y)
  2883. this.y = other.y;
  2884. if (other.z < this.z)
  2885. this.z = other.z;
  2886. return this;
  2887. };
  2888. /**
  2889. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2890. * @param other defines the second operand
  2891. * @returns the current updated Vector3
  2892. */
  2893. Vector3.prototype.maximizeInPlace = function (other) {
  2894. if (other.x > this.x)
  2895. this.x = other.x;
  2896. if (other.y > this.y)
  2897. this.y = other.y;
  2898. if (other.z > this.z)
  2899. this.z = other.z;
  2900. return this;
  2901. };
  2902. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2903. /**
  2904. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2905. */
  2906. get: function () {
  2907. var absX = Math.abs(this.x);
  2908. var absY = Math.abs(this.y);
  2909. if (absX !== absY) {
  2910. return true;
  2911. }
  2912. var absZ = Math.abs(this.z);
  2913. if (absX !== absZ) {
  2914. return true;
  2915. }
  2916. if (absY !== absZ) {
  2917. return true;
  2918. }
  2919. return false;
  2920. },
  2921. enumerable: true,
  2922. configurable: true
  2923. });
  2924. // Properties
  2925. /**
  2926. * Gets the length of the Vector3
  2927. * @returns the length of the Vecto3
  2928. */
  2929. Vector3.prototype.length = function () {
  2930. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2931. };
  2932. /**
  2933. * Gets the squared length of the Vector3
  2934. * @returns squared length of the Vector3
  2935. */
  2936. Vector3.prototype.lengthSquared = function () {
  2937. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2938. };
  2939. /**
  2940. * Normalize the current Vector3.
  2941. * Please note that this is an in place operation.
  2942. * @returns the current updated Vector3
  2943. */
  2944. Vector3.prototype.normalize = function () {
  2945. var len = this.length();
  2946. if (len === 0 || len === 1.0)
  2947. return this;
  2948. var num = 1.0 / len;
  2949. this.x *= num;
  2950. this.y *= num;
  2951. this.z *= num;
  2952. return this;
  2953. };
  2954. /**
  2955. * Normalize the current Vector3 to a new vector
  2956. * @returns the new Vector3
  2957. */
  2958. Vector3.prototype.normalizeToNew = function () {
  2959. var normalized = new Vector3(0, 0, 0);
  2960. this.normalizeToRef(normalized);
  2961. return normalized;
  2962. };
  2963. /**
  2964. * Normalize the current Vector3 to the reference
  2965. * @param reference define the Vector3 to update
  2966. * @returns the updated Vector3
  2967. */
  2968. Vector3.prototype.normalizeToRef = function (reference) {
  2969. var len = this.length();
  2970. if (len === 0 || len === 1.0) {
  2971. reference.set(this.x, this.y, this.z);
  2972. return reference;
  2973. }
  2974. var scale = 1.0 / len;
  2975. this.scaleToRef(scale, reference);
  2976. return reference;
  2977. };
  2978. /**
  2979. * Creates a new Vector3 copied from the current Vector3
  2980. * @returns the new Vector3
  2981. */
  2982. Vector3.prototype.clone = function () {
  2983. return new Vector3(this.x, this.y, this.z);
  2984. };
  2985. /**
  2986. * Copies the passed vector coordinates to the current Vector3 ones
  2987. * @param source defines the source Vector3
  2988. * @returns the current updated Vector3
  2989. */
  2990. Vector3.prototype.copyFrom = function (source) {
  2991. this.x = source.x;
  2992. this.y = source.y;
  2993. this.z = source.z;
  2994. return this;
  2995. };
  2996. /**
  2997. * Copies the passed floats to the current Vector3 coordinates
  2998. * @param x defines the x coordinate of the operand
  2999. * @param y defines the y coordinate of the operand
  3000. * @param z defines the z coordinate of the operand
  3001. * @returns the current updated Vector3
  3002. */
  3003. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3004. this.x = x;
  3005. this.y = y;
  3006. this.z = z;
  3007. return this;
  3008. };
  3009. /**
  3010. * Copies the passed floats to the current Vector3 coordinates
  3011. * @param x defines the x coordinate of the operand
  3012. * @param y defines the y coordinate of the operand
  3013. * @param z defines the z coordinate of the operand
  3014. * @returns the current updated Vector3
  3015. */
  3016. Vector3.prototype.set = function (x, y, z) {
  3017. return this.copyFromFloats(x, y, z);
  3018. };
  3019. // Statics
  3020. /**
  3021. * Get the clip factor between two vectors
  3022. * @param vector0 defines the first operand
  3023. * @param vector1 defines the second operand
  3024. * @param axis defines the axis to use
  3025. * @param size defines the size along the axis
  3026. * @returns the clip factor
  3027. */
  3028. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3029. var d0 = Vector3.Dot(vector0, axis) - size;
  3030. var d1 = Vector3.Dot(vector1, axis) - size;
  3031. var s = d0 / (d0 - d1);
  3032. return s;
  3033. };
  3034. /**
  3035. * Get angle between two vectors
  3036. * @param vector0 angle between vector0 and vector1
  3037. * @param vector1 angle between vector0 and vector1
  3038. * @param normal direction of the normal
  3039. * @return the angle between vector0 and vector1
  3040. */
  3041. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3042. var v0 = vector0.clone().normalize();
  3043. var v1 = vector1.clone().normalize();
  3044. var dot = Vector3.Dot(v0, v1);
  3045. var n = Vector3.Cross(v0, v1);
  3046. if (Vector3.Dot(n, normal) > 0) {
  3047. return Math.acos(dot);
  3048. }
  3049. return -Math.acos(dot);
  3050. };
  3051. /**
  3052. * Returns a new Vector3 set from the index "offset" of the passed array
  3053. * @param array defines the source array
  3054. * @param offset defines the offset in the source array
  3055. * @returns the new Vector3
  3056. */
  3057. Vector3.FromArray = function (array, offset) {
  3058. if (!offset) {
  3059. offset = 0;
  3060. }
  3061. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3062. };
  3063. /**
  3064. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3065. * This function is deprecated. Use FromArray instead
  3066. * @param array defines the source array
  3067. * @param offset defines the offset in the source array
  3068. * @returns the new Vector3
  3069. */
  3070. Vector3.FromFloatArray = function (array, offset) {
  3071. return Vector3.FromArray(array, offset);
  3072. };
  3073. /**
  3074. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3075. * @param array defines the source array
  3076. * @param offset defines the offset in the source array
  3077. * @param result defines the Vector3 where to store the result
  3078. */
  3079. Vector3.FromArrayToRef = function (array, offset, result) {
  3080. result.x = array[offset];
  3081. result.y = array[offset + 1];
  3082. result.z = array[offset + 2];
  3083. };
  3084. /**
  3085. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3086. * This function is deprecated. Use FromArrayToRef instead.
  3087. * @param array defines the source array
  3088. * @param offset defines the offset in the source array
  3089. * @param result defines the Vector3 where to store the result
  3090. */
  3091. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3092. return Vector3.FromArrayToRef(array, offset, result);
  3093. };
  3094. /**
  3095. * Sets the passed vector "result" with the passed floats.
  3096. * @param x defines the x coordinate of the source
  3097. * @param y defines the y coordinate of the source
  3098. * @param z defines the z coordinate of the source
  3099. * @param result defines the Vector3 where to store the result
  3100. */
  3101. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3102. result.x = x;
  3103. result.y = y;
  3104. result.z = z;
  3105. };
  3106. /**
  3107. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3108. * @returns a new empty Vector3
  3109. */
  3110. Vector3.Zero = function () {
  3111. return new Vector3(0.0, 0.0, 0.0);
  3112. };
  3113. /**
  3114. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3115. * @returns a new unit Vector3
  3116. */
  3117. Vector3.One = function () {
  3118. return new Vector3(1.0, 1.0, 1.0);
  3119. };
  3120. /**
  3121. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3122. * @returns a new up Vector3
  3123. */
  3124. Vector3.Up = function () {
  3125. return new Vector3(0.0, 1.0, 0.0);
  3126. };
  3127. /**
  3128. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3129. * @returns a new forward Vector3
  3130. */
  3131. Vector3.Forward = function () {
  3132. return new Vector3(0.0, 0.0, 1.0);
  3133. };
  3134. /**
  3135. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3136. * @returns a new right Vector3
  3137. */
  3138. Vector3.Right = function () {
  3139. return new Vector3(1.0, 0.0, 0.0);
  3140. };
  3141. /**
  3142. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3143. * @returns a new left Vector3
  3144. */
  3145. Vector3.Left = function () {
  3146. return new Vector3(-1.0, 0.0, 0.0);
  3147. };
  3148. /**
  3149. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3150. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3151. * @param vector defines the Vector3 to transform
  3152. * @param transformation defines the transformation matrix
  3153. * @returns the transformed Vector3
  3154. */
  3155. Vector3.TransformCoordinates = function (vector, transformation) {
  3156. var result = Vector3.Zero();
  3157. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3158. return result;
  3159. };
  3160. /**
  3161. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3162. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3163. * @param vector defines the Vector3 to transform
  3164. * @param transformation defines the transformation matrix
  3165. * @param result defines the Vector3 where to store the result
  3166. */
  3167. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3168. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3169. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3170. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3171. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3172. result.x = x / w;
  3173. result.y = y / w;
  3174. result.z = z / w;
  3175. };
  3176. /**
  3177. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3178. * This method computes tranformed coordinates only, not transformed direction vectors
  3179. * @param x define the x coordinate of the source vector
  3180. * @param y define the y coordinate of the source vector
  3181. * @param z define the z coordinate of the source vector
  3182. * @param transformation defines the transformation matrix
  3183. * @param result defines the Vector3 where to store the result
  3184. */
  3185. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3186. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3187. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3188. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3189. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3190. result.x = rx / rw;
  3191. result.y = ry / rw;
  3192. result.z = rz / rw;
  3193. };
  3194. /**
  3195. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3196. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3197. * @param vector defines the Vector3 to transform
  3198. * @param transformation defines the transformation matrix
  3199. * @returns the new Vector3
  3200. */
  3201. Vector3.TransformNormal = function (vector, transformation) {
  3202. var result = Vector3.Zero();
  3203. Vector3.TransformNormalToRef(vector, transformation, result);
  3204. return result;
  3205. };
  3206. /**
  3207. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3208. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3209. * @param vector defines the Vector3 to transform
  3210. * @param transformation defines the transformation matrix
  3211. * @param result defines the Vector3 where to store the result
  3212. */
  3213. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3214. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3215. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3216. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3217. result.x = x;
  3218. result.y = y;
  3219. result.z = z;
  3220. };
  3221. /**
  3222. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3223. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3224. * @param x define the x coordinate of the source vector
  3225. * @param y define the y coordinate of the source vector
  3226. * @param z define the z coordinate of the source vector
  3227. * @param transformation defines the transformation matrix
  3228. * @param result defines the Vector3 where to store the result
  3229. */
  3230. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3231. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3232. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3233. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3234. };
  3235. /**
  3236. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3237. * @param value1 defines the first control point
  3238. * @param value2 defines the second control point
  3239. * @param value3 defines the third control point
  3240. * @param value4 defines the fourth control point
  3241. * @param amount defines the amount on the spline to use
  3242. * @returns the new Vector3
  3243. */
  3244. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3245. var squared = amount * amount;
  3246. var cubed = amount * squared;
  3247. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3248. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3249. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3250. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3251. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3252. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3253. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3254. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3255. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3256. return new Vector3(x, y, z);
  3257. };
  3258. /**
  3259. * 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"
  3260. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3261. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3262. * @param value defines the current value
  3263. * @param min defines the lower range value
  3264. * @param max defines the upper range value
  3265. * @returns the new Vector3
  3266. */
  3267. Vector3.Clamp = function (value, min, max) {
  3268. var x = value.x;
  3269. x = (x > max.x) ? max.x : x;
  3270. x = (x < min.x) ? min.x : x;
  3271. var y = value.y;
  3272. y = (y > max.y) ? max.y : y;
  3273. y = (y < min.y) ? min.y : y;
  3274. var z = value.z;
  3275. z = (z > max.z) ? max.z : z;
  3276. z = (z < min.z) ? min.z : z;
  3277. return new Vector3(x, y, z);
  3278. };
  3279. /**
  3280. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3281. * @param value1 defines the first control point
  3282. * @param tangent1 defines the first tangent vector
  3283. * @param value2 defines the second control point
  3284. * @param tangent2 defines the second tangent vector
  3285. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3286. * @returns the new Vector3
  3287. */
  3288. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3289. var squared = amount * amount;
  3290. var cubed = amount * squared;
  3291. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3292. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3293. var part3 = (cubed - (2.0 * squared)) + amount;
  3294. var part4 = cubed - squared;
  3295. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3296. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3297. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3298. return new Vector3(x, y, z);
  3299. };
  3300. /**
  3301. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3302. * @param start defines the start value
  3303. * @param end defines the end value
  3304. * @param amount max defines amount between both (between 0 and 1)
  3305. * @returns the new Vector3
  3306. */
  3307. Vector3.Lerp = function (start, end, amount) {
  3308. var result = new Vector3(0, 0, 0);
  3309. Vector3.LerpToRef(start, end, amount, result);
  3310. return result;
  3311. };
  3312. /**
  3313. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3314. * @param start defines the start value
  3315. * @param end defines the end value
  3316. * @param amount max defines amount between both (between 0 and 1)
  3317. * @param result defines the Vector3 where to store the result
  3318. */
  3319. Vector3.LerpToRef = function (start, end, amount, result) {
  3320. result.x = start.x + ((end.x - start.x) * amount);
  3321. result.y = start.y + ((end.y - start.y) * amount);
  3322. result.z = start.z + ((end.z - start.z) * amount);
  3323. };
  3324. /**
  3325. * Returns the dot product (float) between the vectors "left" and "right"
  3326. * @param left defines the left operand
  3327. * @param right defines the right operand
  3328. * @returns the dot product
  3329. */
  3330. Vector3.Dot = function (left, right) {
  3331. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3332. };
  3333. /**
  3334. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3335. * The cross product is then orthogonal to both "left" and "right"
  3336. * @param left defines the left operand
  3337. * @param right defines the right operand
  3338. * @returns the cross product
  3339. */
  3340. Vector3.Cross = function (left, right) {
  3341. var result = Vector3.Zero();
  3342. Vector3.CrossToRef(left, right, result);
  3343. return result;
  3344. };
  3345. /**
  3346. * Sets the passed vector "result" with the cross product of "left" and "right"
  3347. * The cross product is then orthogonal to both "left" and "right"
  3348. * @param left defines the left operand
  3349. * @param right defines the right operand
  3350. * @param result defines the Vector3 where to store the result
  3351. */
  3352. Vector3.CrossToRef = function (left, right, result) {
  3353. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3354. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3355. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3356. result.copyFrom(MathTmp.Vector3[0]);
  3357. };
  3358. /**
  3359. * Returns a new Vector3 as the normalization of the passed vector
  3360. * @param vector defines the Vector3 to normalize
  3361. * @returns the new Vector3
  3362. */
  3363. Vector3.Normalize = function (vector) {
  3364. var result = Vector3.Zero();
  3365. Vector3.NormalizeToRef(vector, result);
  3366. return result;
  3367. };
  3368. /**
  3369. * Sets the passed vector "result" with the normalization of the passed first vector
  3370. * @param vector defines the Vector3 to normalize
  3371. * @param result defines the Vector3 where to store the result
  3372. */
  3373. Vector3.NormalizeToRef = function (vector, result) {
  3374. result.copyFrom(vector);
  3375. result.normalize();
  3376. };
  3377. /**
  3378. * Project a Vector3 onto screen space
  3379. * @param vector defines the Vector3 to project
  3380. * @param world defines the world matrix to use
  3381. * @param transform defines the transform (view x projection) matrix to use
  3382. * @param viewport defines the screen viewport to use
  3383. * @returns the new Vector3
  3384. */
  3385. Vector3.Project = function (vector, world, transform, viewport) {
  3386. var cw = viewport.width;
  3387. var ch = viewport.height;
  3388. var cx = viewport.x;
  3389. var cy = viewport.y;
  3390. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3391. 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);
  3392. var matrix = MathTmp.Matrix[0];
  3393. world.multiplyToRef(transform, matrix);
  3394. matrix.multiplyToRef(viewportMatrix, matrix);
  3395. return Vector3.TransformCoordinates(vector, matrix);
  3396. };
  3397. /**
  3398. * Unproject from screen space to object space
  3399. * @param source defines the screen space Vector3 to use
  3400. * @param viewportWidth defines the current width of the viewport
  3401. * @param viewportHeight defines the current height of the viewport
  3402. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3403. * @param transform defines the transform (view x projection) matrix to use
  3404. * @returns the new Vector3
  3405. */
  3406. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3407. var matrix = MathTmp.Matrix[0];
  3408. world.multiplyToRef(transform, matrix);
  3409. matrix.invert();
  3410. source.x = source.x / viewportWidth * 2 - 1;
  3411. source.y = -(source.y / viewportHeight * 2 - 1);
  3412. var vector = Vector3.TransformCoordinates(source, matrix);
  3413. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3414. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3415. vector = vector.scale(1.0 / num);
  3416. }
  3417. return vector;
  3418. };
  3419. /**
  3420. * Unproject from screen space to object space
  3421. * @param source defines the screen space Vector3 to use
  3422. * @param viewportWidth defines the current width of the viewport
  3423. * @param viewportHeight defines the current height of the viewport
  3424. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3425. * @param view defines the view matrix to use
  3426. * @param projection defines the projection matrix to use
  3427. * @returns the new Vector3
  3428. */
  3429. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3430. var result = Vector3.Zero();
  3431. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3432. return result;
  3433. };
  3434. /**
  3435. * Unproject from screen space to object space
  3436. * @param source defines the screen space Vector3 to use
  3437. * @param viewportWidth defines the current width of the viewport
  3438. * @param viewportHeight defines the current height of the viewport
  3439. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3440. * @param view defines the view matrix to use
  3441. * @param projection defines the projection matrix to use
  3442. * @param result defines the Vector3 where to store the result
  3443. */
  3444. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3445. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3446. };
  3447. /**
  3448. * Unproject from screen space to object space
  3449. * @param sourceX defines the screen space x coordinate to use
  3450. * @param sourceY defines the screen space y coordinate to use
  3451. * @param sourceZ defines the screen space z coordinate to use
  3452. * @param viewportWidth defines the current width of the viewport
  3453. * @param viewportHeight defines the current height of the viewport
  3454. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3455. * @param view defines the view matrix to use
  3456. * @param projection defines the projection matrix to use
  3457. * @param result defines the Vector3 where to store the result
  3458. */
  3459. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3460. var matrix = MathTmp.Matrix[0];
  3461. world.multiplyToRef(view, matrix);
  3462. matrix.multiplyToRef(projection, matrix);
  3463. matrix.invert();
  3464. var screenSource = MathTmp.Vector3[0];
  3465. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3466. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3467. screenSource.z = 2 * sourceZ - 1.0;
  3468. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3469. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3470. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3471. result.scaleInPlace(1.0 / num);
  3472. }
  3473. };
  3474. /**
  3475. * Gets the minimal coordinate values between two Vector3
  3476. * @param left defines the first operand
  3477. * @param right defines the second operand
  3478. * @returns the new Vector3
  3479. */
  3480. Vector3.Minimize = function (left, right) {
  3481. var min = left.clone();
  3482. min.minimizeInPlace(right);
  3483. return min;
  3484. };
  3485. /**
  3486. * Gets the maximal coordinate values between two Vector3
  3487. * @param left defines the first operand
  3488. * @param right defines the second operand
  3489. * @returns the new Vector3
  3490. */
  3491. Vector3.Maximize = function (left, right) {
  3492. var max = left.clone();
  3493. max.maximizeInPlace(right);
  3494. return max;
  3495. };
  3496. /**
  3497. * Returns the distance between the vectors "value1" and "value2"
  3498. * @param value1 defines the first operand
  3499. * @param value2 defines the second operand
  3500. * @returns the distance
  3501. */
  3502. Vector3.Distance = function (value1, value2) {
  3503. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3504. };
  3505. /**
  3506. * Returns the squared distance between the vectors "value1" and "value2"
  3507. * @param value1 defines the first operand
  3508. * @param value2 defines the second operand
  3509. * @returns the squared distance
  3510. */
  3511. Vector3.DistanceSquared = function (value1, value2) {
  3512. var x = value1.x - value2.x;
  3513. var y = value1.y - value2.y;
  3514. var z = value1.z - value2.z;
  3515. return (x * x) + (y * y) + (z * z);
  3516. };
  3517. /**
  3518. * Returns a new Vector3 located at the center between "value1" and "value2"
  3519. * @param value1 defines the first operand
  3520. * @param value2 defines the second operand
  3521. * @returns the new Vector3
  3522. */
  3523. Vector3.Center = function (value1, value2) {
  3524. var center = value1.add(value2);
  3525. center.scaleInPlace(0.5);
  3526. return center;
  3527. };
  3528. /**
  3529. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3530. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3531. * to something in order to rotate it from its local system to the given target system
  3532. * Note: axis1, axis2 and axis3 are normalized during this operation
  3533. * @param axis1 defines the first axis
  3534. * @param axis2 defines the second axis
  3535. * @param axis3 defines the third axis
  3536. * @returns a new Vector3
  3537. */
  3538. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3539. var rotation = Vector3.Zero();
  3540. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3541. return rotation;
  3542. };
  3543. /**
  3544. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3545. * @param axis1 defines the first axis
  3546. * @param axis2 defines the second axis
  3547. * @param axis3 defines the third axis
  3548. * @param ref defines the Vector3 where to store the result
  3549. */
  3550. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3551. var quat = MathTmp.Quaternion[0];
  3552. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3553. quat.toEulerAnglesToRef(ref);
  3554. };
  3555. return Vector3;
  3556. }());
  3557. BABYLON.Vector3 = Vector3;
  3558. //Vector4 class created for EulerAngle class conversion to Quaternion
  3559. var Vector4 = /** @class */ (function () {
  3560. /**
  3561. * Creates a Vector4 object from the passed floats.
  3562. */
  3563. function Vector4(x, y, z, w) {
  3564. this.x = x;
  3565. this.y = y;
  3566. this.z = z;
  3567. this.w = w;
  3568. }
  3569. /**
  3570. * Returns the string with the Vector4 coordinates.
  3571. */
  3572. Vector4.prototype.toString = function () {
  3573. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3574. };
  3575. /**
  3576. * Returns the string "Vector4".
  3577. */
  3578. Vector4.prototype.getClassName = function () {
  3579. return "Vector4";
  3580. };
  3581. /**
  3582. * Returns the Vector4 hash code.
  3583. */
  3584. Vector4.prototype.getHashCode = function () {
  3585. var hash = this.x || 0;
  3586. hash = (hash * 397) ^ (this.y || 0);
  3587. hash = (hash * 397) ^ (this.z || 0);
  3588. hash = (hash * 397) ^ (this.w || 0);
  3589. return hash;
  3590. };
  3591. // Operators
  3592. /**
  3593. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3594. */
  3595. Vector4.prototype.asArray = function () {
  3596. var result = new Array();
  3597. this.toArray(result, 0);
  3598. return result;
  3599. };
  3600. /**
  3601. * Populates the passed array from the passed index with the Vector4 coordinates.
  3602. * Returns the Vector4.
  3603. */
  3604. Vector4.prototype.toArray = function (array, index) {
  3605. if (index === undefined) {
  3606. index = 0;
  3607. }
  3608. array[index] = this.x;
  3609. array[index + 1] = this.y;
  3610. array[index + 2] = this.z;
  3611. array[index + 3] = this.w;
  3612. return this;
  3613. };
  3614. /**
  3615. * Adds the passed vector to the current Vector4.
  3616. * Returns the updated Vector4.
  3617. */
  3618. Vector4.prototype.addInPlace = function (otherVector) {
  3619. this.x += otherVector.x;
  3620. this.y += otherVector.y;
  3621. this.z += otherVector.z;
  3622. this.w += otherVector.w;
  3623. return this;
  3624. };
  3625. /**
  3626. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3627. */
  3628. Vector4.prototype.add = function (otherVector) {
  3629. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3630. };
  3631. /**
  3632. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3633. * Returns the current Vector4.
  3634. */
  3635. Vector4.prototype.addToRef = function (otherVector, result) {
  3636. result.x = this.x + otherVector.x;
  3637. result.y = this.y + otherVector.y;
  3638. result.z = this.z + otherVector.z;
  3639. result.w = this.w + otherVector.w;
  3640. return this;
  3641. };
  3642. /**
  3643. * Subtract in place the passed vector from the current Vector4.
  3644. * Returns the updated Vector4.
  3645. */
  3646. Vector4.prototype.subtractInPlace = function (otherVector) {
  3647. this.x -= otherVector.x;
  3648. this.y -= otherVector.y;
  3649. this.z -= otherVector.z;
  3650. this.w -= otherVector.w;
  3651. return this;
  3652. };
  3653. /**
  3654. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3655. */
  3656. Vector4.prototype.subtract = function (otherVector) {
  3657. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3658. };
  3659. /**
  3660. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3661. * Returns the current Vector4.
  3662. */
  3663. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3664. result.x = this.x - otherVector.x;
  3665. result.y = this.y - otherVector.y;
  3666. result.z = this.z - otherVector.z;
  3667. result.w = this.w - otherVector.w;
  3668. return this;
  3669. };
  3670. /**
  3671. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3672. */
  3673. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3674. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3675. };
  3676. /**
  3677. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3678. * Returns the current Vector4.
  3679. */
  3680. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3681. result.x = this.x - x;
  3682. result.y = this.y - y;
  3683. result.z = this.z - z;
  3684. result.w = this.w - w;
  3685. return this;
  3686. };
  3687. /**
  3688. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3689. */
  3690. Vector4.prototype.negate = function () {
  3691. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3692. };
  3693. /**
  3694. * Multiplies the current Vector4 coordinates by scale (float).
  3695. * Returns the updated Vector4.
  3696. */
  3697. Vector4.prototype.scaleInPlace = function (scale) {
  3698. this.x *= scale;
  3699. this.y *= scale;
  3700. this.z *= scale;
  3701. this.w *= scale;
  3702. return this;
  3703. };
  3704. /**
  3705. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3706. */
  3707. Vector4.prototype.scale = function (scale) {
  3708. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3709. };
  3710. /**
  3711. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3712. * Returns the current Vector4.
  3713. */
  3714. Vector4.prototype.scaleToRef = function (scale, result) {
  3715. result.x = this.x * scale;
  3716. result.y = this.y * scale;
  3717. result.z = this.z * scale;
  3718. result.w = this.w * scale;
  3719. return this;
  3720. };
  3721. /**
  3722. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3723. */
  3724. Vector4.prototype.equals = function (otherVector) {
  3725. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3726. };
  3727. /**
  3728. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3729. */
  3730. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3731. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3732. return otherVector
  3733. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3734. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3735. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3736. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3737. };
  3738. /**
  3739. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3740. */
  3741. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3742. return this.x === x && this.y === y && this.z === z && this.w === w;
  3743. };
  3744. /**
  3745. * Multiplies in place the current Vector4 by the passed one.
  3746. * Returns the updated Vector4.
  3747. */
  3748. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3749. this.x *= otherVector.x;
  3750. this.y *= otherVector.y;
  3751. this.z *= otherVector.z;
  3752. this.w *= otherVector.w;
  3753. return this;
  3754. };
  3755. /**
  3756. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3757. */
  3758. Vector4.prototype.multiply = function (otherVector) {
  3759. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3760. };
  3761. /**
  3762. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3763. * Returns the current Vector4.
  3764. */
  3765. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3766. result.x = this.x * otherVector.x;
  3767. result.y = this.y * otherVector.y;
  3768. result.z = this.z * otherVector.z;
  3769. result.w = this.w * otherVector.w;
  3770. return this;
  3771. };
  3772. /**
  3773. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3774. */
  3775. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3776. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3777. };
  3778. /**
  3779. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3780. */
  3781. Vector4.prototype.divide = function (otherVector) {
  3782. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3783. };
  3784. /**
  3785. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3786. * Returns the current Vector4.
  3787. */
  3788. Vector4.prototype.divideToRef = function (otherVector, result) {
  3789. result.x = this.x / otherVector.x;
  3790. result.y = this.y / otherVector.y;
  3791. result.z = this.z / otherVector.z;
  3792. result.w = this.w / otherVector.w;
  3793. return this;
  3794. };
  3795. /**
  3796. * Divides the current Vector3 coordinates by the passed ones.
  3797. * @returns the updated Vector3.
  3798. */
  3799. Vector4.prototype.divideInPlace = function (otherVector) {
  3800. return this.divideToRef(otherVector, this);
  3801. };
  3802. /**
  3803. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3804. * @param other defines the second operand
  3805. * @returns the current updated Vector4
  3806. */
  3807. Vector4.prototype.minimizeInPlace = function (other) {
  3808. if (other.x < this.x)
  3809. this.x = other.x;
  3810. if (other.y < this.y)
  3811. this.y = other.y;
  3812. if (other.z < this.z)
  3813. this.z = other.z;
  3814. if (other.w < this.w)
  3815. this.w = other.w;
  3816. return this;
  3817. };
  3818. /**
  3819. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3820. * @param other defines the second operand
  3821. * @returns the current updated Vector4
  3822. */
  3823. Vector4.prototype.maximizeInPlace = function (other) {
  3824. if (other.x > this.x)
  3825. this.x = other.x;
  3826. if (other.y > this.y)
  3827. this.y = other.y;
  3828. if (other.z > this.z)
  3829. this.z = other.z;
  3830. if (other.w > this.w)
  3831. this.w = other.w;
  3832. return this;
  3833. };
  3834. // Properties
  3835. /**
  3836. * Returns the Vector4 length (float).
  3837. */
  3838. Vector4.prototype.length = function () {
  3839. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3840. };
  3841. /**
  3842. * Returns the Vector4 squared length (float).
  3843. */
  3844. Vector4.prototype.lengthSquared = function () {
  3845. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3846. };
  3847. // Methods
  3848. /**
  3849. * Normalizes in place the Vector4.
  3850. * Returns the updated Vector4.
  3851. */
  3852. Vector4.prototype.normalize = function () {
  3853. var len = this.length();
  3854. if (len === 0)
  3855. return this;
  3856. var num = 1.0 / len;
  3857. this.x *= num;
  3858. this.y *= num;
  3859. this.z *= num;
  3860. this.w *= num;
  3861. return this;
  3862. };
  3863. /**
  3864. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3865. */
  3866. Vector4.prototype.toVector3 = function () {
  3867. return new Vector3(this.x, this.y, this.z);
  3868. };
  3869. /**
  3870. * Returns a new Vector4 copied from the current one.
  3871. */
  3872. Vector4.prototype.clone = function () {
  3873. return new Vector4(this.x, this.y, this.z, this.w);
  3874. };
  3875. /**
  3876. * Updates the current Vector4 with the passed one coordinates.
  3877. * Returns the updated Vector4.
  3878. */
  3879. Vector4.prototype.copyFrom = function (source) {
  3880. this.x = source.x;
  3881. this.y = source.y;
  3882. this.z = source.z;
  3883. this.w = source.w;
  3884. return this;
  3885. };
  3886. /**
  3887. * Updates the current Vector4 coordinates with the passed floats.
  3888. * Returns the updated Vector4.
  3889. */
  3890. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3891. this.x = x;
  3892. this.y = y;
  3893. this.z = z;
  3894. this.w = w;
  3895. return this;
  3896. };
  3897. /**
  3898. * Updates the current Vector4 coordinates with the passed floats.
  3899. * Returns the updated Vector4.
  3900. */
  3901. Vector4.prototype.set = function (x, y, z, w) {
  3902. return this.copyFromFloats(x, y, z, w);
  3903. };
  3904. // Statics
  3905. /**
  3906. * Returns a new Vector4 set from the starting index of the passed array.
  3907. */
  3908. Vector4.FromArray = function (array, offset) {
  3909. if (!offset) {
  3910. offset = 0;
  3911. }
  3912. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3913. };
  3914. /**
  3915. * Updates the passed vector "result" from the starting index of the passed array.
  3916. */
  3917. Vector4.FromArrayToRef = function (array, offset, result) {
  3918. result.x = array[offset];
  3919. result.y = array[offset + 1];
  3920. result.z = array[offset + 2];
  3921. result.w = array[offset + 3];
  3922. };
  3923. /**
  3924. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3925. */
  3926. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3927. Vector4.FromArrayToRef(array, offset, result);
  3928. };
  3929. /**
  3930. * Updates the passed vector "result" coordinates from the passed floats.
  3931. */
  3932. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3933. result.x = x;
  3934. result.y = y;
  3935. result.z = z;
  3936. result.w = w;
  3937. };
  3938. /**
  3939. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3940. */
  3941. Vector4.Zero = function () {
  3942. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3943. };
  3944. /**
  3945. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3946. */
  3947. Vector4.One = function () {
  3948. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3949. };
  3950. /**
  3951. * Returns a new normalized Vector4 from the passed one.
  3952. */
  3953. Vector4.Normalize = function (vector) {
  3954. var result = Vector4.Zero();
  3955. Vector4.NormalizeToRef(vector, result);
  3956. return result;
  3957. };
  3958. /**
  3959. * Updates the passed vector "result" from the normalization of the passed one.
  3960. */
  3961. Vector4.NormalizeToRef = function (vector, result) {
  3962. result.copyFrom(vector);
  3963. result.normalize();
  3964. };
  3965. Vector4.Minimize = function (left, right) {
  3966. var min = left.clone();
  3967. min.minimizeInPlace(right);
  3968. return min;
  3969. };
  3970. Vector4.Maximize = function (left, right) {
  3971. var max = left.clone();
  3972. max.maximizeInPlace(right);
  3973. return max;
  3974. };
  3975. /**
  3976. * Returns the distance (float) between the vectors "value1" and "value2".
  3977. */
  3978. Vector4.Distance = function (value1, value2) {
  3979. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3980. };
  3981. /**
  3982. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3983. */
  3984. Vector4.DistanceSquared = function (value1, value2) {
  3985. var x = value1.x - value2.x;
  3986. var y = value1.y - value2.y;
  3987. var z = value1.z - value2.z;
  3988. var w = value1.w - value2.w;
  3989. return (x * x) + (y * y) + (z * z) + (w * w);
  3990. };
  3991. /**
  3992. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3993. */
  3994. Vector4.Center = function (value1, value2) {
  3995. var center = value1.add(value2);
  3996. center.scaleInPlace(0.5);
  3997. return center;
  3998. };
  3999. /**
  4000. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4001. * This methods computes transformed normalized direction vectors only.
  4002. */
  4003. Vector4.TransformNormal = function (vector, transformation) {
  4004. var result = Vector4.Zero();
  4005. Vector4.TransformNormalToRef(vector, transformation, result);
  4006. return result;
  4007. };
  4008. /**
  4009. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4010. * This methods computes transformed normalized direction vectors only.
  4011. */
  4012. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4013. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4014. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4015. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4016. result.x = x;
  4017. result.y = y;
  4018. result.z = z;
  4019. result.w = vector.w;
  4020. };
  4021. /**
  4022. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4023. * This methods computes transformed normalized direction vectors only.
  4024. */
  4025. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4026. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4027. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4028. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4029. result.w = w;
  4030. };
  4031. return Vector4;
  4032. }());
  4033. BABYLON.Vector4 = Vector4;
  4034. var Size = /** @class */ (function () {
  4035. /**
  4036. * Creates a Size object from the passed width and height (floats).
  4037. */
  4038. function Size(width, height) {
  4039. this.width = width;
  4040. this.height = height;
  4041. }
  4042. // Returns a string with the Size width and height.
  4043. Size.prototype.toString = function () {
  4044. return "{W: " + this.width + ", H: " + this.height + "}";
  4045. };
  4046. /**
  4047. * Returns the string "Size"
  4048. */
  4049. Size.prototype.getClassName = function () {
  4050. return "Size";
  4051. };
  4052. /**
  4053. * Returns the Size hash code.
  4054. */
  4055. Size.prototype.getHashCode = function () {
  4056. var hash = this.width || 0;
  4057. hash = (hash * 397) ^ (this.height || 0);
  4058. return hash;
  4059. };
  4060. /**
  4061. * Updates the current size from the passed one.
  4062. * Returns the updated Size.
  4063. */
  4064. Size.prototype.copyFrom = function (src) {
  4065. this.width = src.width;
  4066. this.height = src.height;
  4067. };
  4068. /**
  4069. * Updates in place the current Size from the passed floats.
  4070. * Returns the updated Size.
  4071. */
  4072. Size.prototype.copyFromFloats = function (width, height) {
  4073. this.width = width;
  4074. this.height = height;
  4075. return this;
  4076. };
  4077. /**
  4078. * Updates in place the current Size from the passed floats.
  4079. * Returns the updated Size.
  4080. */
  4081. Size.prototype.set = function (width, height) {
  4082. return this.copyFromFloats(width, height);
  4083. };
  4084. /**
  4085. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4086. */
  4087. Size.prototype.multiplyByFloats = function (w, h) {
  4088. return new Size(this.width * w, this.height * h);
  4089. };
  4090. /**
  4091. * Returns a new Size copied from the passed one.
  4092. */
  4093. Size.prototype.clone = function () {
  4094. return new Size(this.width, this.height);
  4095. };
  4096. /**
  4097. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4098. */
  4099. Size.prototype.equals = function (other) {
  4100. if (!other) {
  4101. return false;
  4102. }
  4103. return (this.width === other.width) && (this.height === other.height);
  4104. };
  4105. Object.defineProperty(Size.prototype, "surface", {
  4106. /**
  4107. * Returns the surface of the Size : width * height (float).
  4108. */
  4109. get: function () {
  4110. return this.width * this.height;
  4111. },
  4112. enumerable: true,
  4113. configurable: true
  4114. });
  4115. /**
  4116. * Returns a new Size set to (0.0, 0.0)
  4117. */
  4118. Size.Zero = function () {
  4119. return new Size(0.0, 0.0);
  4120. };
  4121. /**
  4122. * Returns a new Size set as the addition result of the current Size and the passed one.
  4123. */
  4124. Size.prototype.add = function (otherSize) {
  4125. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4126. return r;
  4127. };
  4128. /**
  4129. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4130. */
  4131. Size.prototype.subtract = function (otherSize) {
  4132. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4133. return r;
  4134. };
  4135. /**
  4136. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4137. */
  4138. Size.Lerp = function (start, end, amount) {
  4139. var w = start.width + ((end.width - start.width) * amount);
  4140. var h = start.height + ((end.height - start.height) * amount);
  4141. return new Size(w, h);
  4142. };
  4143. return Size;
  4144. }());
  4145. BABYLON.Size = Size;
  4146. var Quaternion = /** @class */ (function () {
  4147. /**
  4148. * Creates a new Quaternion from the passed floats.
  4149. */
  4150. function Quaternion(x, y, z, w) {
  4151. if (x === void 0) { x = 0.0; }
  4152. if (y === void 0) { y = 0.0; }
  4153. if (z === void 0) { z = 0.0; }
  4154. if (w === void 0) { w = 1.0; }
  4155. this.x = x;
  4156. this.y = y;
  4157. this.z = z;
  4158. this.w = w;
  4159. }
  4160. /**
  4161. * Returns a string with the Quaternion coordinates.
  4162. */
  4163. Quaternion.prototype.toString = function () {
  4164. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4165. };
  4166. /**
  4167. * Returns the string "Quaternion".
  4168. */
  4169. Quaternion.prototype.getClassName = function () {
  4170. return "Quaternion";
  4171. };
  4172. /**
  4173. * Returns the Quaternion hash code.
  4174. */
  4175. Quaternion.prototype.getHashCode = function () {
  4176. var hash = this.x || 0;
  4177. hash = (hash * 397) ^ (this.y || 0);
  4178. hash = (hash * 397) ^ (this.z || 0);
  4179. hash = (hash * 397) ^ (this.w || 0);
  4180. return hash;
  4181. };
  4182. /**
  4183. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4184. */
  4185. Quaternion.prototype.asArray = function () {
  4186. return [this.x, this.y, this.z, this.w];
  4187. };
  4188. /**
  4189. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4190. */
  4191. Quaternion.prototype.equals = function (otherQuaternion) {
  4192. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4193. };
  4194. /**
  4195. * Returns a new Quaternion copied from the current one.
  4196. */
  4197. Quaternion.prototype.clone = function () {
  4198. return new Quaternion(this.x, this.y, this.z, this.w);
  4199. };
  4200. /**
  4201. * Updates the current Quaternion from the passed one coordinates.
  4202. * Returns the updated Quaterion.
  4203. */
  4204. Quaternion.prototype.copyFrom = function (other) {
  4205. this.x = other.x;
  4206. this.y = other.y;
  4207. this.z = other.z;
  4208. this.w = other.w;
  4209. return this;
  4210. };
  4211. /**
  4212. * Updates the current Quaternion from the passed float coordinates.
  4213. * Returns the updated Quaterion.
  4214. */
  4215. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4216. this.x = x;
  4217. this.y = y;
  4218. this.z = z;
  4219. this.w = w;
  4220. return this;
  4221. };
  4222. /**
  4223. * Updates the current Quaternion from the passed float coordinates.
  4224. * Returns the updated Quaterion.
  4225. */
  4226. Quaternion.prototype.set = function (x, y, z, w) {
  4227. return this.copyFromFloats(x, y, z, w);
  4228. };
  4229. /**
  4230. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4231. */
  4232. Quaternion.prototype.add = function (other) {
  4233. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4234. };
  4235. /**
  4236. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4237. */
  4238. Quaternion.prototype.subtract = function (other) {
  4239. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4240. };
  4241. /**
  4242. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4243. */
  4244. Quaternion.prototype.scale = function (value) {
  4245. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4246. };
  4247. /**
  4248. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4249. */
  4250. Quaternion.prototype.multiply = function (q1) {
  4251. var result = new Quaternion(0, 0, 0, 1.0);
  4252. this.multiplyToRef(q1, result);
  4253. return result;
  4254. };
  4255. /**
  4256. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4257. * Returns the current Quaternion.
  4258. */
  4259. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4260. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4261. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4262. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4263. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4264. result.copyFromFloats(x, y, z, w);
  4265. return this;
  4266. };
  4267. /**
  4268. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4269. * Returns the updated Quaternion.
  4270. */
  4271. Quaternion.prototype.multiplyInPlace = function (q1) {
  4272. this.multiplyToRef(q1, this);
  4273. return this;
  4274. };
  4275. /**
  4276. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4277. * Returns the current Quaternion.
  4278. */
  4279. Quaternion.prototype.conjugateToRef = function (ref) {
  4280. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4281. return this;
  4282. };
  4283. /**
  4284. * Conjugates in place the current Quaternion.
  4285. * Returns the updated Quaternion.
  4286. */
  4287. Quaternion.prototype.conjugateInPlace = function () {
  4288. this.x *= -1;
  4289. this.y *= -1;
  4290. this.z *= -1;
  4291. return this;
  4292. };
  4293. /**
  4294. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4295. */
  4296. Quaternion.prototype.conjugate = function () {
  4297. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4298. return result;
  4299. };
  4300. /**
  4301. * Returns the Quaternion length (float).
  4302. */
  4303. Quaternion.prototype.length = function () {
  4304. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4305. };
  4306. /**
  4307. * Normalize in place the current Quaternion.
  4308. * Returns the updated Quaternion.
  4309. */
  4310. Quaternion.prototype.normalize = function () {
  4311. var length = 1.0 / this.length();
  4312. this.x *= length;
  4313. this.y *= length;
  4314. this.z *= length;
  4315. this.w *= length;
  4316. return this;
  4317. };
  4318. /**
  4319. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  4320. */
  4321. Quaternion.prototype.toEulerAngles = function (order) {
  4322. if (order === void 0) { order = "YZX"; }
  4323. var result = Vector3.Zero();
  4324. this.toEulerAnglesToRef(result, order);
  4325. return result;
  4326. };
  4327. /**
  4328. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  4329. * Returns the current Quaternion.
  4330. */
  4331. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4332. if (order === void 0) { order = "YZX"; }
  4333. var qz = this.z;
  4334. var qx = this.x;
  4335. var qy = this.y;
  4336. var qw = this.w;
  4337. var sqw = qw * qw;
  4338. var sqz = qz * qz;
  4339. var sqx = qx * qx;
  4340. var sqy = qy * qy;
  4341. var zAxisY = qy * qz - qx * qw;
  4342. var limit = .4999999;
  4343. if (zAxisY < -limit) {
  4344. result.y = 2 * Math.atan2(qy, qw);
  4345. result.x = Math.PI / 2;
  4346. result.z = 0;
  4347. }
  4348. else if (zAxisY > limit) {
  4349. result.y = 2 * Math.atan2(qy, qw);
  4350. result.x = -Math.PI / 2;
  4351. result.z = 0;
  4352. }
  4353. else {
  4354. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4355. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4356. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4357. }
  4358. return this;
  4359. };
  4360. /**
  4361. * Updates the passed rotation matrix with the current Quaternion values.
  4362. * Returns the current Quaternion.
  4363. */
  4364. Quaternion.prototype.toRotationMatrix = function (result) {
  4365. var xx = this.x * this.x;
  4366. var yy = this.y * this.y;
  4367. var zz = this.z * this.z;
  4368. var xy = this.x * this.y;
  4369. var zw = this.z * this.w;
  4370. var zx = this.z * this.x;
  4371. var yw = this.y * this.w;
  4372. var yz = this.y * this.z;
  4373. var xw = this.x * this.w;
  4374. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4375. result.m[1] = 2.0 * (xy + zw);
  4376. result.m[2] = 2.0 * (zx - yw);
  4377. result.m[3] = 0;
  4378. result.m[4] = 2.0 * (xy - zw);
  4379. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4380. result.m[6] = 2.0 * (yz + xw);
  4381. result.m[7] = 0;
  4382. result.m[8] = 2.0 * (zx + yw);
  4383. result.m[9] = 2.0 * (yz - xw);
  4384. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4385. result.m[11] = 0;
  4386. result.m[12] = 0;
  4387. result.m[13] = 0;
  4388. result.m[14] = 0;
  4389. result.m[15] = 1.0;
  4390. result._markAsUpdated();
  4391. return this;
  4392. };
  4393. /**
  4394. * Updates the current Quaternion from the passed rotation matrix values.
  4395. * Returns the updated Quaternion.
  4396. */
  4397. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4398. Quaternion.FromRotationMatrixToRef(matrix, this);
  4399. return this;
  4400. };
  4401. // Statics
  4402. /**
  4403. * Returns a new Quaternion set from the passed rotation matrix values.
  4404. */
  4405. Quaternion.FromRotationMatrix = function (matrix) {
  4406. var result = new Quaternion();
  4407. Quaternion.FromRotationMatrixToRef(matrix, result);
  4408. return result;
  4409. };
  4410. /**
  4411. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4412. */
  4413. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4414. var data = matrix.m;
  4415. var m11 = data[0], m12 = data[4], m13 = data[8];
  4416. var m21 = data[1], m22 = data[5], m23 = data[9];
  4417. var m31 = data[2], m32 = data[6], m33 = data[10];
  4418. var trace = m11 + m22 + m33;
  4419. var s;
  4420. if (trace > 0) {
  4421. s = 0.5 / Math.sqrt(trace + 1.0);
  4422. result.w = 0.25 / s;
  4423. result.x = (m32 - m23) * s;
  4424. result.y = (m13 - m31) * s;
  4425. result.z = (m21 - m12) * s;
  4426. }
  4427. else if (m11 > m22 && m11 > m33) {
  4428. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4429. result.w = (m32 - m23) / s;
  4430. result.x = 0.25 * s;
  4431. result.y = (m12 + m21) / s;
  4432. result.z = (m13 + m31) / s;
  4433. }
  4434. else if (m22 > m33) {
  4435. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4436. result.w = (m13 - m31) / s;
  4437. result.x = (m12 + m21) / s;
  4438. result.y = 0.25 * s;
  4439. result.z = (m23 + m32) / s;
  4440. }
  4441. else {
  4442. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4443. result.w = (m21 - m12) / s;
  4444. result.x = (m13 + m31) / s;
  4445. result.y = (m23 + m32) / s;
  4446. result.z = 0.25 * s;
  4447. }
  4448. };
  4449. /**
  4450. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4451. */
  4452. Quaternion.Zero = function () {
  4453. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4454. };
  4455. /**
  4456. * Returns a new Quaternion as the inverted current Quaternion.
  4457. */
  4458. Quaternion.Inverse = function (q) {
  4459. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4460. };
  4461. /**
  4462. * Returns the identity Quaternion.
  4463. */
  4464. Quaternion.Identity = function () {
  4465. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4466. };
  4467. Quaternion.IsIdentity = function (quaternion) {
  4468. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4469. };
  4470. /**
  4471. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4472. */
  4473. Quaternion.RotationAxis = function (axis, angle) {
  4474. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4475. };
  4476. /**
  4477. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4478. */
  4479. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4480. var sin = Math.sin(angle / 2);
  4481. axis.normalize();
  4482. result.w = Math.cos(angle / 2);
  4483. result.x = axis.x * sin;
  4484. result.y = axis.y * sin;
  4485. result.z = axis.z * sin;
  4486. return result;
  4487. };
  4488. /**
  4489. * Retuns a new Quaternion set from the starting index of the passed array.
  4490. */
  4491. Quaternion.FromArray = function (array, offset) {
  4492. if (!offset) {
  4493. offset = 0;
  4494. }
  4495. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4496. };
  4497. /**
  4498. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4499. */
  4500. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4501. var q = new Quaternion();
  4502. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4503. return q;
  4504. };
  4505. /**
  4506. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4507. */
  4508. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4509. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4510. var halfRoll = roll * 0.5;
  4511. var halfPitch = pitch * 0.5;
  4512. var halfYaw = yaw * 0.5;
  4513. var sinRoll = Math.sin(halfRoll);
  4514. var cosRoll = Math.cos(halfRoll);
  4515. var sinPitch = Math.sin(halfPitch);
  4516. var cosPitch = Math.cos(halfPitch);
  4517. var sinYaw = Math.sin(halfYaw);
  4518. var cosYaw = Math.cos(halfYaw);
  4519. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4520. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4521. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4522. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4523. };
  4524. /**
  4525. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4526. */
  4527. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4528. var result = new Quaternion();
  4529. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4530. return result;
  4531. };
  4532. /**
  4533. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4534. */
  4535. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4536. // Produces a quaternion from Euler angles in the z-x-z orientation
  4537. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4538. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4539. var halfBeta = beta * 0.5;
  4540. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4541. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4542. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4543. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4544. };
  4545. /**
  4546. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4547. * cf to Vector3.RotationFromAxis() documentation.
  4548. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4549. */
  4550. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4551. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4552. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4553. return quat;
  4554. };
  4555. /**
  4556. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4557. * cf to Vector3.RotationFromAxis() documentation.
  4558. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4559. */
  4560. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4561. var rotMat = MathTmp.Matrix[0];
  4562. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4563. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4564. };
  4565. Quaternion.Slerp = function (left, right, amount) {
  4566. var result = Quaternion.Identity();
  4567. Quaternion.SlerpToRef(left, right, amount, result);
  4568. return result;
  4569. };
  4570. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4571. var num2;
  4572. var num3;
  4573. var num = amount;
  4574. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4575. var flag = false;
  4576. if (num4 < 0) {
  4577. flag = true;
  4578. num4 = -num4;
  4579. }
  4580. if (num4 > 0.999999) {
  4581. num3 = 1 - num;
  4582. num2 = flag ? -num : num;
  4583. }
  4584. else {
  4585. var num5 = Math.acos(num4);
  4586. var num6 = (1.0 / Math.sin(num5));
  4587. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4588. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4589. }
  4590. result.x = (num3 * left.x) + (num2 * right.x);
  4591. result.y = (num3 * left.y) + (num2 * right.y);
  4592. result.z = (num3 * left.z) + (num2 * right.z);
  4593. result.w = (num3 * left.w) + (num2 * right.w);
  4594. };
  4595. /**
  4596. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4597. */
  4598. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4599. var squared = amount * amount;
  4600. var cubed = amount * squared;
  4601. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4602. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4603. var part3 = (cubed - (2.0 * squared)) + amount;
  4604. var part4 = cubed - squared;
  4605. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4606. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4607. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4608. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4609. return new Quaternion(x, y, z, w);
  4610. };
  4611. return Quaternion;
  4612. }());
  4613. BABYLON.Quaternion = Quaternion;
  4614. var Matrix = /** @class */ (function () {
  4615. function Matrix() {
  4616. this._isIdentity = false;
  4617. this._isIdentityDirty = true;
  4618. this.m = new Float32Array(16);
  4619. this._markAsUpdated();
  4620. }
  4621. Matrix.prototype._markAsUpdated = function () {
  4622. this.updateFlag = Matrix._updateFlagSeed++;
  4623. this._isIdentityDirty = true;
  4624. };
  4625. // Properties
  4626. /**
  4627. * Boolean : True is the matrix is the identity matrix
  4628. */
  4629. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4630. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4631. if (this._isIdentityDirty) {
  4632. this._isIdentityDirty = false;
  4633. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4634. this._isIdentity = false;
  4635. }
  4636. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4637. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4638. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4639. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4640. this._isIdentity = false;
  4641. }
  4642. else {
  4643. this._isIdentity = true;
  4644. }
  4645. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4646. this._isIdentity = false;
  4647. }
  4648. }
  4649. return this._isIdentity;
  4650. };
  4651. /**
  4652. * Returns the matrix determinant (float).
  4653. */
  4654. Matrix.prototype.determinant = function () {
  4655. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4656. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4657. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4658. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4659. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4660. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4661. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4662. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4663. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4664. };
  4665. // Methods
  4666. /**
  4667. * Returns the matrix underlying array.
  4668. */
  4669. Matrix.prototype.toArray = function () {
  4670. return this.m;
  4671. };
  4672. /**
  4673. * Returns the matrix underlying array.
  4674. */
  4675. Matrix.prototype.asArray = function () {
  4676. return this.toArray();
  4677. };
  4678. /**
  4679. * Inverts in place the Matrix.
  4680. * Returns the Matrix inverted.
  4681. */
  4682. Matrix.prototype.invert = function () {
  4683. this.invertToRef(this);
  4684. return this;
  4685. };
  4686. /**
  4687. * Sets all the matrix elements to zero.
  4688. * Returns the Matrix.
  4689. */
  4690. Matrix.prototype.reset = function () {
  4691. for (var index = 0; index < 16; index++) {
  4692. this.m[index] = 0.0;
  4693. }
  4694. this._markAsUpdated();
  4695. return this;
  4696. };
  4697. /**
  4698. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4699. */
  4700. Matrix.prototype.add = function (other) {
  4701. var result = new Matrix();
  4702. this.addToRef(other, result);
  4703. return result;
  4704. };
  4705. /**
  4706. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4707. * Returns the Matrix.
  4708. */
  4709. Matrix.prototype.addToRef = function (other, result) {
  4710. for (var index = 0; index < 16; index++) {
  4711. result.m[index] = this.m[index] + other.m[index];
  4712. }
  4713. result._markAsUpdated();
  4714. return this;
  4715. };
  4716. /**
  4717. * Adds in place the passed matrix to the current Matrix.
  4718. * Returns the updated Matrix.
  4719. */
  4720. Matrix.prototype.addToSelf = function (other) {
  4721. for (var index = 0; index < 16; index++) {
  4722. this.m[index] += other.m[index];
  4723. }
  4724. this._markAsUpdated();
  4725. return this;
  4726. };
  4727. /**
  4728. * Sets the passed matrix with the current inverted Matrix.
  4729. * Returns the unmodified current Matrix.
  4730. */
  4731. Matrix.prototype.invertToRef = function (other) {
  4732. var l1 = this.m[0];
  4733. var l2 = this.m[1];
  4734. var l3 = this.m[2];
  4735. var l4 = this.m[3];
  4736. var l5 = this.m[4];
  4737. var l6 = this.m[5];
  4738. var l7 = this.m[6];
  4739. var l8 = this.m[7];
  4740. var l9 = this.m[8];
  4741. var l10 = this.m[9];
  4742. var l11 = this.m[10];
  4743. var l12 = this.m[11];
  4744. var l13 = this.m[12];
  4745. var l14 = this.m[13];
  4746. var l15 = this.m[14];
  4747. var l16 = this.m[15];
  4748. var l17 = (l11 * l16) - (l12 * l15);
  4749. var l18 = (l10 * l16) - (l12 * l14);
  4750. var l19 = (l10 * l15) - (l11 * l14);
  4751. var l20 = (l9 * l16) - (l12 * l13);
  4752. var l21 = (l9 * l15) - (l11 * l13);
  4753. var l22 = (l9 * l14) - (l10 * l13);
  4754. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4755. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4756. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4757. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4758. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4759. var l28 = (l7 * l16) - (l8 * l15);
  4760. var l29 = (l6 * l16) - (l8 * l14);
  4761. var l30 = (l6 * l15) - (l7 * l14);
  4762. var l31 = (l5 * l16) - (l8 * l13);
  4763. var l32 = (l5 * l15) - (l7 * l13);
  4764. var l33 = (l5 * l14) - (l6 * l13);
  4765. var l34 = (l7 * l12) - (l8 * l11);
  4766. var l35 = (l6 * l12) - (l8 * l10);
  4767. var l36 = (l6 * l11) - (l7 * l10);
  4768. var l37 = (l5 * l12) - (l8 * l9);
  4769. var l38 = (l5 * l11) - (l7 * l9);
  4770. var l39 = (l5 * l10) - (l6 * l9);
  4771. other.m[0] = l23 * l27;
  4772. other.m[4] = l24 * l27;
  4773. other.m[8] = l25 * l27;
  4774. other.m[12] = l26 * l27;
  4775. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4776. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4777. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4778. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4779. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4780. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4781. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4782. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4783. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4784. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4785. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4786. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4787. other._markAsUpdated();
  4788. return this;
  4789. };
  4790. /**
  4791. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4792. * Returns the updated Matrix.
  4793. */
  4794. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4795. this.m[12] = x;
  4796. this.m[13] = y;
  4797. this.m[14] = z;
  4798. this._markAsUpdated();
  4799. return this;
  4800. };
  4801. /**
  4802. * Inserts the translation vector in the current Matrix.
  4803. * Returns the updated Matrix.
  4804. */
  4805. Matrix.prototype.setTranslation = function (vector3) {
  4806. this.m[12] = vector3.x;
  4807. this.m[13] = vector3.y;
  4808. this.m[14] = vector3.z;
  4809. this._markAsUpdated();
  4810. return this;
  4811. };
  4812. /**
  4813. * Returns a new Vector3 as the extracted translation from the Matrix.
  4814. */
  4815. Matrix.prototype.getTranslation = function () {
  4816. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4817. };
  4818. /**
  4819. * Fill a Vector3 with the extracted translation from the Matrix.
  4820. */
  4821. Matrix.prototype.getTranslationToRef = function (result) {
  4822. result.x = this.m[12];
  4823. result.y = this.m[13];
  4824. result.z = this.m[14];
  4825. return this;
  4826. };
  4827. /**
  4828. * Remove rotation and scaling part from the Matrix.
  4829. * Returns the updated Matrix.
  4830. */
  4831. Matrix.prototype.removeRotationAndScaling = function () {
  4832. this.setRowFromFloats(0, 1, 0, 0, 0);
  4833. this.setRowFromFloats(1, 0, 1, 0, 0);
  4834. this.setRowFromFloats(2, 0, 0, 1, 0);
  4835. return this;
  4836. };
  4837. /**
  4838. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4839. */
  4840. Matrix.prototype.multiply = function (other) {
  4841. var result = new Matrix();
  4842. this.multiplyToRef(other, result);
  4843. return result;
  4844. };
  4845. /**
  4846. * Updates the current Matrix from the passed one values.
  4847. * Returns the updated Matrix.
  4848. */
  4849. Matrix.prototype.copyFrom = function (other) {
  4850. for (var index = 0; index < 16; index++) {
  4851. this.m[index] = other.m[index];
  4852. }
  4853. this._markAsUpdated();
  4854. return this;
  4855. };
  4856. /**
  4857. * Populates the passed array from the starting index with the Matrix values.
  4858. * Returns the Matrix.
  4859. */
  4860. Matrix.prototype.copyToArray = function (array, offset) {
  4861. if (offset === void 0) { offset = 0; }
  4862. for (var index = 0; index < 16; index++) {
  4863. array[offset + index] = this.m[index];
  4864. }
  4865. return this;
  4866. };
  4867. /**
  4868. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4869. */
  4870. Matrix.prototype.multiplyToRef = function (other, result) {
  4871. this.multiplyToArray(other, result.m, 0);
  4872. result._markAsUpdated();
  4873. return this;
  4874. };
  4875. /**
  4876. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4877. */
  4878. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4879. var tm0 = this.m[0];
  4880. var tm1 = this.m[1];
  4881. var tm2 = this.m[2];
  4882. var tm3 = this.m[3];
  4883. var tm4 = this.m[4];
  4884. var tm5 = this.m[5];
  4885. var tm6 = this.m[6];
  4886. var tm7 = this.m[7];
  4887. var tm8 = this.m[8];
  4888. var tm9 = this.m[9];
  4889. var tm10 = this.m[10];
  4890. var tm11 = this.m[11];
  4891. var tm12 = this.m[12];
  4892. var tm13 = this.m[13];
  4893. var tm14 = this.m[14];
  4894. var tm15 = this.m[15];
  4895. var om0 = other.m[0];
  4896. var om1 = other.m[1];
  4897. var om2 = other.m[2];
  4898. var om3 = other.m[3];
  4899. var om4 = other.m[4];
  4900. var om5 = other.m[5];
  4901. var om6 = other.m[6];
  4902. var om7 = other.m[7];
  4903. var om8 = other.m[8];
  4904. var om9 = other.m[9];
  4905. var om10 = other.m[10];
  4906. var om11 = other.m[11];
  4907. var om12 = other.m[12];
  4908. var om13 = other.m[13];
  4909. var om14 = other.m[14];
  4910. var om15 = other.m[15];
  4911. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4912. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4913. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4914. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4915. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4916. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4917. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4918. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4919. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4920. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4921. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4922. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4923. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4924. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4925. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4926. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4927. return this;
  4928. };
  4929. /**
  4930. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4931. */
  4932. Matrix.prototype.equals = function (value) {
  4933. return value &&
  4934. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4935. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4936. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4937. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4938. };
  4939. /**
  4940. * Returns a new Matrix from the current Matrix.
  4941. */
  4942. Matrix.prototype.clone = function () {
  4943. 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]);
  4944. };
  4945. /**
  4946. * Returns the string "Matrix"
  4947. */
  4948. Matrix.prototype.getClassName = function () {
  4949. return "Matrix";
  4950. };
  4951. /**
  4952. * Returns the Matrix hash code.
  4953. */
  4954. Matrix.prototype.getHashCode = function () {
  4955. var hash = this.m[0] || 0;
  4956. for (var i = 1; i < 16; i++) {
  4957. hash = (hash * 397) ^ (this.m[i] || 0);
  4958. }
  4959. return hash;
  4960. };
  4961. /**
  4962. * Decomposes the current Matrix into :
  4963. * - a scale vector3 passed as a reference to update,
  4964. * - a rotation quaternion passed as a reference to update,
  4965. * - a translation vector3 passed as a reference to update.
  4966. * Returns the true if operation was successful.
  4967. */
  4968. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4969. translation.x = this.m[12];
  4970. translation.y = this.m[13];
  4971. translation.z = this.m[14];
  4972. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4973. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4974. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4975. if (this.determinant() <= 0) {
  4976. scale.y *= -1;
  4977. }
  4978. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4979. rotation.x = 0;
  4980. rotation.y = 0;
  4981. rotation.z = 0;
  4982. rotation.w = 1;
  4983. return false;
  4984. }
  4985. 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]);
  4986. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4987. return true;
  4988. };
  4989. /**
  4990. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  4991. * @param ref matrix to store the result
  4992. */
  4993. Matrix.prototype.toNormalMatrix = function (ref) {
  4994. this.invertToRef(ref);
  4995. ref.transpose();
  4996. var m = ref.m;
  4997. 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);
  4998. };
  4999. /**
  5000. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5001. */
  5002. Matrix.prototype.getRotationMatrix = function () {
  5003. var result = Matrix.Identity();
  5004. this.getRotationMatrixToRef(result);
  5005. return result;
  5006. };
  5007. /**
  5008. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5009. * Returns the current Matrix.
  5010. */
  5011. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5012. var m = this.m;
  5013. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5014. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5015. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5016. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5017. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5018. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5019. 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);
  5020. return this;
  5021. };
  5022. // Statics
  5023. /**
  5024. * Returns a new Matrix set from the starting index of the passed array.
  5025. */
  5026. Matrix.FromArray = function (array, offset) {
  5027. var result = new Matrix();
  5028. if (!offset) {
  5029. offset = 0;
  5030. }
  5031. Matrix.FromArrayToRef(array, offset, result);
  5032. return result;
  5033. };
  5034. /**
  5035. * Sets the passed "result" matrix from the starting index of the passed array.
  5036. */
  5037. Matrix.FromArrayToRef = function (array, offset, result) {
  5038. for (var index = 0; index < 16; index++) {
  5039. result.m[index] = array[index + offset];
  5040. }
  5041. result._markAsUpdated();
  5042. };
  5043. /**
  5044. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5045. */
  5046. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5047. for (var index = 0; index < 16; index++) {
  5048. result.m[index] = array[index + offset] * scale;
  5049. }
  5050. result._markAsUpdated();
  5051. };
  5052. /**
  5053. * Sets the passed matrix "result" with the 16 passed floats.
  5054. */
  5055. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5056. result.m[0] = initialM11;
  5057. result.m[1] = initialM12;
  5058. result.m[2] = initialM13;
  5059. result.m[3] = initialM14;
  5060. result.m[4] = initialM21;
  5061. result.m[5] = initialM22;
  5062. result.m[6] = initialM23;
  5063. result.m[7] = initialM24;
  5064. result.m[8] = initialM31;
  5065. result.m[9] = initialM32;
  5066. result.m[10] = initialM33;
  5067. result.m[11] = initialM34;
  5068. result.m[12] = initialM41;
  5069. result.m[13] = initialM42;
  5070. result.m[14] = initialM43;
  5071. result.m[15] = initialM44;
  5072. result._markAsUpdated();
  5073. };
  5074. /**
  5075. * Returns the index-th row of the current matrix as a new Vector4.
  5076. */
  5077. Matrix.prototype.getRow = function (index) {
  5078. if (index < 0 || index > 3) {
  5079. return null;
  5080. }
  5081. var i = index * 4;
  5082. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5083. };
  5084. /**
  5085. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5086. * Returns the updated Matrix.
  5087. */
  5088. Matrix.prototype.setRow = function (index, row) {
  5089. if (index < 0 || index > 3) {
  5090. return this;
  5091. }
  5092. var i = index * 4;
  5093. this.m[i + 0] = row.x;
  5094. this.m[i + 1] = row.y;
  5095. this.m[i + 2] = row.z;
  5096. this.m[i + 3] = row.w;
  5097. this._markAsUpdated();
  5098. return this;
  5099. };
  5100. /**
  5101. * Compute the transpose of the matrix.
  5102. * Returns a new Matrix.
  5103. */
  5104. Matrix.prototype.transpose = function () {
  5105. return Matrix.Transpose(this);
  5106. };
  5107. /**
  5108. * Compute the transpose of the matrix.
  5109. * Returns the current matrix.
  5110. */
  5111. Matrix.prototype.transposeToRef = function (result) {
  5112. Matrix.TransposeToRef(this, result);
  5113. return this;
  5114. };
  5115. /**
  5116. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5117. * Returns the updated Matrix.
  5118. */
  5119. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5120. if (index < 0 || index > 3) {
  5121. return this;
  5122. }
  5123. var i = index * 4;
  5124. this.m[i + 0] = x;
  5125. this.m[i + 1] = y;
  5126. this.m[i + 2] = z;
  5127. this.m[i + 3] = w;
  5128. this._markAsUpdated();
  5129. return this;
  5130. };
  5131. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5132. /**
  5133. * Static identity matrix to be used as readonly matrix
  5134. * Must not be updated.
  5135. */
  5136. get: function () {
  5137. return Matrix._identityReadOnly;
  5138. },
  5139. enumerable: true,
  5140. configurable: true
  5141. });
  5142. /**
  5143. * Returns a new Matrix set from the 16 passed floats.
  5144. */
  5145. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5146. var result = new Matrix();
  5147. result.m[0] = initialM11;
  5148. result.m[1] = initialM12;
  5149. result.m[2] = initialM13;
  5150. result.m[3] = initialM14;
  5151. result.m[4] = initialM21;
  5152. result.m[5] = initialM22;
  5153. result.m[6] = initialM23;
  5154. result.m[7] = initialM24;
  5155. result.m[8] = initialM31;
  5156. result.m[9] = initialM32;
  5157. result.m[10] = initialM33;
  5158. result.m[11] = initialM34;
  5159. result.m[12] = initialM41;
  5160. result.m[13] = initialM42;
  5161. result.m[14] = initialM43;
  5162. result.m[15] = initialM44;
  5163. return result;
  5164. };
  5165. /**
  5166. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5167. */
  5168. Matrix.Compose = function (scale, rotation, translation) {
  5169. var result = Matrix.Identity();
  5170. Matrix.ComposeToRef(scale, rotation, translation, result);
  5171. return result;
  5172. };
  5173. /**
  5174. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5175. */
  5176. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5177. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5178. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5179. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5180. result.setTranslation(translation);
  5181. };
  5182. /**
  5183. * Returns a new indentity Matrix.
  5184. */
  5185. Matrix.Identity = function () {
  5186. 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);
  5187. };
  5188. /**
  5189. * Sets the passed "result" as an identity matrix.
  5190. */
  5191. Matrix.IdentityToRef = function (result) {
  5192. 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);
  5193. };
  5194. /**
  5195. * Returns a new zero Matrix.
  5196. */
  5197. Matrix.Zero = function () {
  5198. 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);
  5199. };
  5200. /**
  5201. * Returns a new rotation matrix for "angle" radians around the X axis.
  5202. */
  5203. Matrix.RotationX = function (angle) {
  5204. var result = new Matrix();
  5205. Matrix.RotationXToRef(angle, result);
  5206. return result;
  5207. };
  5208. /**
  5209. * Returns a new Matrix as the passed inverted one.
  5210. */
  5211. Matrix.Invert = function (source) {
  5212. var result = new Matrix();
  5213. source.invertToRef(result);
  5214. return result;
  5215. };
  5216. /**
  5217. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5218. */
  5219. Matrix.RotationXToRef = function (angle, result) {
  5220. var s = Math.sin(angle);
  5221. var c = Math.cos(angle);
  5222. result.m[0] = 1.0;
  5223. result.m[15] = 1.0;
  5224. result.m[5] = c;
  5225. result.m[10] = c;
  5226. result.m[9] = -s;
  5227. result.m[6] = s;
  5228. result.m[1] = 0.0;
  5229. result.m[2] = 0.0;
  5230. result.m[3] = 0.0;
  5231. result.m[4] = 0.0;
  5232. result.m[7] = 0.0;
  5233. result.m[8] = 0.0;
  5234. result.m[11] = 0.0;
  5235. result.m[12] = 0.0;
  5236. result.m[13] = 0.0;
  5237. result.m[14] = 0.0;
  5238. result._markAsUpdated();
  5239. };
  5240. /**
  5241. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5242. */
  5243. Matrix.RotationY = function (angle) {
  5244. var result = new Matrix();
  5245. Matrix.RotationYToRef(angle, result);
  5246. return result;
  5247. };
  5248. /**
  5249. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5250. */
  5251. Matrix.RotationYToRef = function (angle, result) {
  5252. var s = Math.sin(angle);
  5253. var c = Math.cos(angle);
  5254. result.m[5] = 1.0;
  5255. result.m[15] = 1.0;
  5256. result.m[0] = c;
  5257. result.m[2] = -s;
  5258. result.m[8] = s;
  5259. result.m[10] = c;
  5260. result.m[1] = 0.0;
  5261. result.m[3] = 0.0;
  5262. result.m[4] = 0.0;
  5263. result.m[6] = 0.0;
  5264. result.m[7] = 0.0;
  5265. result.m[9] = 0.0;
  5266. result.m[11] = 0.0;
  5267. result.m[12] = 0.0;
  5268. result.m[13] = 0.0;
  5269. result.m[14] = 0.0;
  5270. result._markAsUpdated();
  5271. };
  5272. /**
  5273. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5274. */
  5275. Matrix.RotationZ = function (angle) {
  5276. var result = new Matrix();
  5277. Matrix.RotationZToRef(angle, result);
  5278. return result;
  5279. };
  5280. /**
  5281. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5282. */
  5283. Matrix.RotationZToRef = function (angle, result) {
  5284. var s = Math.sin(angle);
  5285. var c = Math.cos(angle);
  5286. result.m[10] = 1.0;
  5287. result.m[15] = 1.0;
  5288. result.m[0] = c;
  5289. result.m[1] = s;
  5290. result.m[4] = -s;
  5291. result.m[5] = c;
  5292. result.m[2] = 0.0;
  5293. result.m[3] = 0.0;
  5294. result.m[6] = 0.0;
  5295. result.m[7] = 0.0;
  5296. result.m[8] = 0.0;
  5297. result.m[9] = 0.0;
  5298. result.m[11] = 0.0;
  5299. result.m[12] = 0.0;
  5300. result.m[13] = 0.0;
  5301. result.m[14] = 0.0;
  5302. result._markAsUpdated();
  5303. };
  5304. /**
  5305. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5306. */
  5307. Matrix.RotationAxis = function (axis, angle) {
  5308. var result = Matrix.Zero();
  5309. Matrix.RotationAxisToRef(axis, angle, result);
  5310. return result;
  5311. };
  5312. /**
  5313. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5314. */
  5315. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5316. var s = Math.sin(-angle);
  5317. var c = Math.cos(-angle);
  5318. var c1 = 1 - c;
  5319. axis.normalize();
  5320. result.m[0] = (axis.x * axis.x) * c1 + c;
  5321. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5322. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5323. result.m[3] = 0.0;
  5324. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5325. result.m[5] = (axis.y * axis.y) * c1 + c;
  5326. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5327. result.m[7] = 0.0;
  5328. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5329. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5330. result.m[10] = (axis.z * axis.z) * c1 + c;
  5331. result.m[11] = 0.0;
  5332. result.m[15] = 1.0;
  5333. result._markAsUpdated();
  5334. };
  5335. /**
  5336. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5337. */
  5338. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5339. var result = new Matrix();
  5340. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5341. return result;
  5342. };
  5343. /**
  5344. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5345. */
  5346. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5347. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5348. this._tempQuaternion.toRotationMatrix(result);
  5349. };
  5350. /**
  5351. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5352. */
  5353. Matrix.Scaling = function (x, y, z) {
  5354. var result = Matrix.Zero();
  5355. Matrix.ScalingToRef(x, y, z, result);
  5356. return result;
  5357. };
  5358. /**
  5359. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5360. */
  5361. Matrix.ScalingToRef = function (x, y, z, result) {
  5362. result.m[0] = x;
  5363. result.m[1] = 0.0;
  5364. result.m[2] = 0.0;
  5365. result.m[3] = 0.0;
  5366. result.m[4] = 0.0;
  5367. result.m[5] = y;
  5368. result.m[6] = 0.0;
  5369. result.m[7] = 0.0;
  5370. result.m[8] = 0.0;
  5371. result.m[9] = 0.0;
  5372. result.m[10] = z;
  5373. result.m[11] = 0.0;
  5374. result.m[12] = 0.0;
  5375. result.m[13] = 0.0;
  5376. result.m[14] = 0.0;
  5377. result.m[15] = 1.0;
  5378. result._markAsUpdated();
  5379. };
  5380. /**
  5381. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5382. */
  5383. Matrix.Translation = function (x, y, z) {
  5384. var result = Matrix.Identity();
  5385. Matrix.TranslationToRef(x, y, z, result);
  5386. return result;
  5387. };
  5388. /**
  5389. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5390. */
  5391. Matrix.TranslationToRef = function (x, y, z, result) {
  5392. 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);
  5393. };
  5394. /**
  5395. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  5396. */
  5397. Matrix.Lerp = function (startValue, endValue, gradient) {
  5398. var result = Matrix.Zero();
  5399. for (var index = 0; index < 16; index++) {
  5400. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5401. }
  5402. result._markAsUpdated();
  5403. return result;
  5404. };
  5405. /**
  5406. * Returns a new Matrix whose values are computed by :
  5407. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5408. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5409. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5410. */
  5411. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5412. var startScale = new Vector3(0, 0, 0);
  5413. var startRotation = new Quaternion();
  5414. var startTranslation = new Vector3(0, 0, 0);
  5415. startValue.decompose(startScale, startRotation, startTranslation);
  5416. var endScale = new Vector3(0, 0, 0);
  5417. var endRotation = new Quaternion();
  5418. var endTranslation = new Vector3(0, 0, 0);
  5419. endValue.decompose(endScale, endRotation, endTranslation);
  5420. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5421. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5422. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5423. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5424. };
  5425. /**
  5426. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5427. * This methods works for a Left-Handed system.
  5428. */
  5429. Matrix.LookAtLH = function (eye, target, up) {
  5430. var result = Matrix.Zero();
  5431. Matrix.LookAtLHToRef(eye, target, up, result);
  5432. return result;
  5433. };
  5434. /**
  5435. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5436. * This methods works for a Left-Handed system.
  5437. */
  5438. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5439. // Z axis
  5440. target.subtractToRef(eye, this._zAxis);
  5441. this._zAxis.normalize();
  5442. // X axis
  5443. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5444. if (this._xAxis.lengthSquared() === 0) {
  5445. this._xAxis.x = 1.0;
  5446. }
  5447. else {
  5448. this._xAxis.normalize();
  5449. }
  5450. // Y axis
  5451. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5452. this._yAxis.normalize();
  5453. // Eye angles
  5454. var ex = -Vector3.Dot(this._xAxis, eye);
  5455. var ey = -Vector3.Dot(this._yAxis, eye);
  5456. var ez = -Vector3.Dot(this._zAxis, eye);
  5457. 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);
  5458. };
  5459. /**
  5460. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5461. * This methods works for a Right-Handed system.
  5462. */
  5463. Matrix.LookAtRH = function (eye, target, up) {
  5464. var result = Matrix.Zero();
  5465. Matrix.LookAtRHToRef(eye, target, up, result);
  5466. return result;
  5467. };
  5468. /**
  5469. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5470. * This methods works for a Left-Handed system.
  5471. */
  5472. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5473. // Z axis
  5474. eye.subtractToRef(target, this._zAxis);
  5475. this._zAxis.normalize();
  5476. // X axis
  5477. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5478. if (this._xAxis.lengthSquared() === 0) {
  5479. this._xAxis.x = 1.0;
  5480. }
  5481. else {
  5482. this._xAxis.normalize();
  5483. }
  5484. // Y axis
  5485. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5486. this._yAxis.normalize();
  5487. // Eye angles
  5488. var ex = -Vector3.Dot(this._xAxis, eye);
  5489. var ey = -Vector3.Dot(this._yAxis, eye);
  5490. var ez = -Vector3.Dot(this._zAxis, eye);
  5491. 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);
  5492. };
  5493. /**
  5494. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5495. */
  5496. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5497. var matrix = Matrix.Zero();
  5498. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5499. return matrix;
  5500. };
  5501. /**
  5502. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5503. */
  5504. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5505. var n = znear;
  5506. var f = zfar;
  5507. var a = 2.0 / width;
  5508. var b = 2.0 / height;
  5509. var c = 2.0 / (f - n);
  5510. var d = -(f + n) / (f - n);
  5511. 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);
  5512. };
  5513. /**
  5514. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5515. */
  5516. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5517. var matrix = Matrix.Zero();
  5518. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5519. return matrix;
  5520. };
  5521. /**
  5522. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5523. */
  5524. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5525. var n = znear;
  5526. var f = zfar;
  5527. var a = 2.0 / (right - left);
  5528. var b = 2.0 / (top - bottom);
  5529. var c = 2.0 / (f - n);
  5530. var d = -(f + n) / (f - n);
  5531. var i0 = (left + right) / (left - right);
  5532. var i1 = (top + bottom) / (bottom - top);
  5533. 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);
  5534. };
  5535. /**
  5536. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5537. */
  5538. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5539. var matrix = Matrix.Zero();
  5540. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5541. return matrix;
  5542. };
  5543. /**
  5544. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5545. */
  5546. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5547. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5548. result.m[10] *= -1.0;
  5549. };
  5550. /**
  5551. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5552. */
  5553. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5554. var matrix = Matrix.Zero();
  5555. var n = znear;
  5556. var f = zfar;
  5557. var a = 2.0 * n / width;
  5558. var b = 2.0 * n / height;
  5559. var c = (f + n) / (f - n);
  5560. var d = -2.0 * f * n / (f - n);
  5561. 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);
  5562. return matrix;
  5563. };
  5564. /**
  5565. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5566. */
  5567. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5568. var matrix = Matrix.Zero();
  5569. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5570. return matrix;
  5571. };
  5572. /**
  5573. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5574. */
  5575. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5576. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5577. var n = znear;
  5578. var f = zfar;
  5579. var t = 1.0 / (Math.tan(fov * 0.5));
  5580. var a = isVerticalFovFixed ? (t / aspect) : t;
  5581. var b = isVerticalFovFixed ? t : (t * aspect);
  5582. var c = (f + n) / (f - n);
  5583. var d = -2.0 * f * n / (f - n);
  5584. 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);
  5585. };
  5586. /**
  5587. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5588. */
  5589. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5590. var matrix = Matrix.Zero();
  5591. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5592. return matrix;
  5593. };
  5594. /**
  5595. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5596. */
  5597. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5598. //alternatively this could be expressed as:
  5599. // m = PerspectiveFovLHToRef
  5600. // m[10] *= -1.0;
  5601. // m[11] *= -1.0;
  5602. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5603. var n = znear;
  5604. var f = zfar;
  5605. var t = 1.0 / (Math.tan(fov * 0.5));
  5606. var a = isVerticalFovFixed ? (t / aspect) : t;
  5607. var b = isVerticalFovFixed ? t : (t * aspect);
  5608. var c = -(f + n) / (f - n);
  5609. var d = -2 * f * n / (f - n);
  5610. 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);
  5611. };
  5612. /**
  5613. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5614. */
  5615. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5616. if (rightHanded === void 0) { rightHanded = false; }
  5617. var rightHandedFactor = rightHanded ? -1 : 1;
  5618. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5619. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5620. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5621. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5622. var xScale = 2.0 / (leftTan + rightTan);
  5623. var yScale = 2.0 / (upTan + downTan);
  5624. result.m[0] = xScale;
  5625. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5626. result.m[5] = yScale;
  5627. result.m[6] = result.m[7] = 0.0;
  5628. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5629. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5630. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5631. result.m[10] = -zfar / (znear - zfar);
  5632. result.m[11] = 1.0 * rightHandedFactor;
  5633. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5634. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5635. // result.m[14] = (znear * zfar) / (znear - zfar);
  5636. result._markAsUpdated();
  5637. };
  5638. /**
  5639. * Returns the final transformation matrix : world * view * projection * viewport
  5640. */
  5641. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5642. var cw = viewport.width;
  5643. var ch = viewport.height;
  5644. var cx = viewport.x;
  5645. var cy = viewport.y;
  5646. 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);
  5647. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5648. };
  5649. /**
  5650. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5651. */
  5652. Matrix.GetAsMatrix2x2 = function (matrix) {
  5653. return new Float32Array([
  5654. matrix.m[0], matrix.m[1],
  5655. matrix.m[4], matrix.m[5]
  5656. ]);
  5657. };
  5658. /**
  5659. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5660. */
  5661. Matrix.GetAsMatrix3x3 = function (matrix) {
  5662. return new Float32Array([
  5663. matrix.m[0], matrix.m[1], matrix.m[2],
  5664. matrix.m[4], matrix.m[5], matrix.m[6],
  5665. matrix.m[8], matrix.m[9], matrix.m[10]
  5666. ]);
  5667. };
  5668. /**
  5669. * Compute the transpose of the passed Matrix.
  5670. * Returns a new Matrix.
  5671. */
  5672. Matrix.Transpose = function (matrix) {
  5673. var result = new Matrix();
  5674. Matrix.TransposeToRef(matrix, result);
  5675. return result;
  5676. };
  5677. /**
  5678. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5679. */
  5680. Matrix.TransposeToRef = function (matrix, result) {
  5681. result.m[0] = matrix.m[0];
  5682. result.m[1] = matrix.m[4];
  5683. result.m[2] = matrix.m[8];
  5684. result.m[3] = matrix.m[12];
  5685. result.m[4] = matrix.m[1];
  5686. result.m[5] = matrix.m[5];
  5687. result.m[6] = matrix.m[9];
  5688. result.m[7] = matrix.m[13];
  5689. result.m[8] = matrix.m[2];
  5690. result.m[9] = matrix.m[6];
  5691. result.m[10] = matrix.m[10];
  5692. result.m[11] = matrix.m[14];
  5693. result.m[12] = matrix.m[3];
  5694. result.m[13] = matrix.m[7];
  5695. result.m[14] = matrix.m[11];
  5696. result.m[15] = matrix.m[15];
  5697. };
  5698. /**
  5699. * Returns a new Matrix as the reflection matrix across the passed plane.
  5700. */
  5701. Matrix.Reflection = function (plane) {
  5702. var matrix = new Matrix();
  5703. Matrix.ReflectionToRef(plane, matrix);
  5704. return matrix;
  5705. };
  5706. /**
  5707. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5708. */
  5709. Matrix.ReflectionToRef = function (plane, result) {
  5710. plane.normalize();
  5711. var x = plane.normal.x;
  5712. var y = plane.normal.y;
  5713. var z = plane.normal.z;
  5714. var temp = -2 * x;
  5715. var temp2 = -2 * y;
  5716. var temp3 = -2 * z;
  5717. result.m[0] = (temp * x) + 1;
  5718. result.m[1] = temp2 * x;
  5719. result.m[2] = temp3 * x;
  5720. result.m[3] = 0.0;
  5721. result.m[4] = temp * y;
  5722. result.m[5] = (temp2 * y) + 1;
  5723. result.m[6] = temp3 * y;
  5724. result.m[7] = 0.0;
  5725. result.m[8] = temp * z;
  5726. result.m[9] = temp2 * z;
  5727. result.m[10] = (temp3 * z) + 1;
  5728. result.m[11] = 0.0;
  5729. result.m[12] = temp * plane.d;
  5730. result.m[13] = temp2 * plane.d;
  5731. result.m[14] = temp3 * plane.d;
  5732. result.m[15] = 1.0;
  5733. result._markAsUpdated();
  5734. };
  5735. /**
  5736. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5737. */
  5738. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5739. result.m[0] = xaxis.x;
  5740. result.m[1] = xaxis.y;
  5741. result.m[2] = xaxis.z;
  5742. result.m[3] = 0.0;
  5743. result.m[4] = yaxis.x;
  5744. result.m[5] = yaxis.y;
  5745. result.m[6] = yaxis.z;
  5746. result.m[7] = 0.0;
  5747. result.m[8] = zaxis.x;
  5748. result.m[9] = zaxis.y;
  5749. result.m[10] = zaxis.z;
  5750. result.m[11] = 0.0;
  5751. result.m[12] = 0.0;
  5752. result.m[13] = 0.0;
  5753. result.m[14] = 0.0;
  5754. result.m[15] = 1.0;
  5755. result._markAsUpdated();
  5756. };
  5757. /**
  5758. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5759. */
  5760. Matrix.FromQuaternionToRef = function (quat, result) {
  5761. var xx = quat.x * quat.x;
  5762. var yy = quat.y * quat.y;
  5763. var zz = quat.z * quat.z;
  5764. var xy = quat.x * quat.y;
  5765. var zw = quat.z * quat.w;
  5766. var zx = quat.z * quat.x;
  5767. var yw = quat.y * quat.w;
  5768. var yz = quat.y * quat.z;
  5769. var xw = quat.x * quat.w;
  5770. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5771. result.m[1] = 2.0 * (xy + zw);
  5772. result.m[2] = 2.0 * (zx - yw);
  5773. result.m[3] = 0.0;
  5774. result.m[4] = 2.0 * (xy - zw);
  5775. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5776. result.m[6] = 2.0 * (yz + xw);
  5777. result.m[7] = 0.0;
  5778. result.m[8] = 2.0 * (zx + yw);
  5779. result.m[9] = 2.0 * (yz - xw);
  5780. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5781. result.m[11] = 0.0;
  5782. result.m[12] = 0.0;
  5783. result.m[13] = 0.0;
  5784. result.m[14] = 0.0;
  5785. result.m[15] = 1.0;
  5786. result._markAsUpdated();
  5787. };
  5788. Matrix._tempQuaternion = new Quaternion();
  5789. Matrix._xAxis = Vector3.Zero();
  5790. Matrix._yAxis = Vector3.Zero();
  5791. Matrix._zAxis = Vector3.Zero();
  5792. Matrix._updateFlagSeed = 0;
  5793. Matrix._identityReadOnly = Matrix.Identity();
  5794. return Matrix;
  5795. }());
  5796. BABYLON.Matrix = Matrix;
  5797. var Plane = /** @class */ (function () {
  5798. /**
  5799. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5800. */
  5801. function Plane(a, b, c, d) {
  5802. this.normal = new Vector3(a, b, c);
  5803. this.d = d;
  5804. }
  5805. /**
  5806. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5807. */
  5808. Plane.prototype.asArray = function () {
  5809. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5810. };
  5811. // Methods
  5812. /**
  5813. * Returns a new plane copied from the current Plane.
  5814. */
  5815. Plane.prototype.clone = function () {
  5816. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5817. };
  5818. /**
  5819. * Returns the string "Plane".
  5820. */
  5821. Plane.prototype.getClassName = function () {
  5822. return "Plane";
  5823. };
  5824. /**
  5825. * Returns the Plane hash code.
  5826. */
  5827. Plane.prototype.getHashCode = function () {
  5828. var hash = this.normal.getHashCode();
  5829. hash = (hash * 397) ^ (this.d || 0);
  5830. return hash;
  5831. };
  5832. /**
  5833. * Normalize the current Plane in place.
  5834. * Returns the updated Plane.
  5835. */
  5836. Plane.prototype.normalize = function () {
  5837. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5838. var magnitude = 0.0;
  5839. if (norm !== 0) {
  5840. magnitude = 1.0 / norm;
  5841. }
  5842. this.normal.x *= magnitude;
  5843. this.normal.y *= magnitude;
  5844. this.normal.z *= magnitude;
  5845. this.d *= magnitude;
  5846. return this;
  5847. };
  5848. /**
  5849. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5850. */
  5851. Plane.prototype.transform = function (transformation) {
  5852. var transposedMatrix = Matrix.Transpose(transformation);
  5853. var x = this.normal.x;
  5854. var y = this.normal.y;
  5855. var z = this.normal.z;
  5856. var d = this.d;
  5857. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5858. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5859. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5860. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5861. return new Plane(normalX, normalY, normalZ, finalD);
  5862. };
  5863. /**
  5864. * Returns the dot product (float) of the point coordinates and the plane normal.
  5865. */
  5866. Plane.prototype.dotCoordinate = function (point) {
  5867. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5868. };
  5869. /**
  5870. * Updates the current Plane from the plane defined by the three passed points.
  5871. * Returns the updated Plane.
  5872. */
  5873. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5874. var x1 = point2.x - point1.x;
  5875. var y1 = point2.y - point1.y;
  5876. var z1 = point2.z - point1.z;
  5877. var x2 = point3.x - point1.x;
  5878. var y2 = point3.y - point1.y;
  5879. var z2 = point3.z - point1.z;
  5880. var yz = (y1 * z2) - (z1 * y2);
  5881. var xz = (z1 * x2) - (x1 * z2);
  5882. var xy = (x1 * y2) - (y1 * x2);
  5883. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5884. var invPyth;
  5885. if (pyth !== 0) {
  5886. invPyth = 1.0 / pyth;
  5887. }
  5888. else {
  5889. invPyth = 0.0;
  5890. }
  5891. this.normal.x = yz * invPyth;
  5892. this.normal.y = xz * invPyth;
  5893. this.normal.z = xy * invPyth;
  5894. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5895. return this;
  5896. };
  5897. /**
  5898. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5899. */
  5900. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5901. var dot = Vector3.Dot(this.normal, direction);
  5902. return (dot <= epsilon);
  5903. };
  5904. /**
  5905. * Returns the signed distance (float) from the passed point to the Plane.
  5906. */
  5907. Plane.prototype.signedDistanceTo = function (point) {
  5908. return Vector3.Dot(point, this.normal) + this.d;
  5909. };
  5910. // Statics
  5911. /**
  5912. * Returns a new Plane from the passed array.
  5913. */
  5914. Plane.FromArray = function (array) {
  5915. return new Plane(array[0], array[1], array[2], array[3]);
  5916. };
  5917. /**
  5918. * Returns a new Plane defined by the three passed points.
  5919. */
  5920. Plane.FromPoints = function (point1, point2, point3) {
  5921. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5922. result.copyFromPoints(point1, point2, point3);
  5923. return result;
  5924. };
  5925. /**
  5926. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5927. * Note : the vector "normal" is updated because normalized.
  5928. */
  5929. Plane.FromPositionAndNormal = function (origin, normal) {
  5930. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5931. normal.normalize();
  5932. result.normal = normal;
  5933. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5934. return result;
  5935. };
  5936. /**
  5937. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5938. */
  5939. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5940. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5941. return Vector3.Dot(point, normal) + d;
  5942. };
  5943. return Plane;
  5944. }());
  5945. BABYLON.Plane = Plane;
  5946. var Viewport = /** @class */ (function () {
  5947. /**
  5948. * Creates a Viewport object located at (x, y) and sized (width, height).
  5949. */
  5950. function Viewport(x, y, width, height) {
  5951. this.x = x;
  5952. this.y = y;
  5953. this.width = width;
  5954. this.height = height;
  5955. }
  5956. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5957. if (renderWidthOrEngine.getRenderWidth) {
  5958. var engine = renderWidthOrEngine;
  5959. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5960. }
  5961. var renderWidth = renderWidthOrEngine;
  5962. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5963. };
  5964. /**
  5965. * Returns a new Viewport copied from the current one.
  5966. */
  5967. Viewport.prototype.clone = function () {
  5968. return new Viewport(this.x, this.y, this.width, this.height);
  5969. };
  5970. return Viewport;
  5971. }());
  5972. BABYLON.Viewport = Viewport;
  5973. var Frustum = /** @class */ (function () {
  5974. function Frustum() {
  5975. }
  5976. /**
  5977. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5978. */
  5979. Frustum.GetPlanes = function (transform) {
  5980. var frustumPlanes = [];
  5981. for (var index = 0; index < 6; index++) {
  5982. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5983. }
  5984. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5985. return frustumPlanes;
  5986. };
  5987. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5988. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5989. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5990. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5991. frustumPlane.d = transform.m[15] + transform.m[14];
  5992. frustumPlane.normalize();
  5993. };
  5994. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5995. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5996. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5997. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  5998. frustumPlane.d = transform.m[15] - transform.m[14];
  5999. frustumPlane.normalize();
  6000. };
  6001. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6002. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6003. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6004. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6005. frustumPlane.d = transform.m[15] + transform.m[12];
  6006. frustumPlane.normalize();
  6007. };
  6008. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6009. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6010. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6011. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6012. frustumPlane.d = transform.m[15] - transform.m[12];
  6013. frustumPlane.normalize();
  6014. };
  6015. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6016. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6017. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6018. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6019. frustumPlane.d = transform.m[15] - transform.m[13];
  6020. frustumPlane.normalize();
  6021. };
  6022. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6023. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6024. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6025. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6026. frustumPlane.d = transform.m[15] + transform.m[13];
  6027. frustumPlane.normalize();
  6028. };
  6029. /**
  6030. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6031. */
  6032. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6033. // Near
  6034. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6035. // Far
  6036. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6037. // Left
  6038. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6039. // Right
  6040. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6041. // Top
  6042. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6043. // Bottom
  6044. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6045. };
  6046. return Frustum;
  6047. }());
  6048. BABYLON.Frustum = Frustum;
  6049. var Space;
  6050. (function (Space) {
  6051. Space[Space["LOCAL"] = 0] = "LOCAL";
  6052. Space[Space["WORLD"] = 1] = "WORLD";
  6053. Space[Space["BONE"] = 2] = "BONE";
  6054. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6055. var Axis = /** @class */ (function () {
  6056. function Axis() {
  6057. }
  6058. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6059. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6060. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6061. return Axis;
  6062. }());
  6063. BABYLON.Axis = Axis;
  6064. ;
  6065. var BezierCurve = /** @class */ (function () {
  6066. function BezierCurve() {
  6067. }
  6068. /**
  6069. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6070. */
  6071. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6072. // Extract X (which is equal to time here)
  6073. var f0 = 1 - 3 * x2 + 3 * x1;
  6074. var f1 = 3 * x2 - 6 * x1;
  6075. var f2 = 3 * x1;
  6076. var refinedT = t;
  6077. for (var i = 0; i < 5; i++) {
  6078. var refinedT2 = refinedT * refinedT;
  6079. var refinedT3 = refinedT2 * refinedT;
  6080. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6081. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6082. refinedT -= (x - t) * slope;
  6083. refinedT = Math.min(1, Math.max(0, refinedT));
  6084. }
  6085. // Resolve cubic bezier for the given x
  6086. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6087. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6088. Math.pow(refinedT, 3);
  6089. };
  6090. return BezierCurve;
  6091. }());
  6092. BABYLON.BezierCurve = BezierCurve;
  6093. var Orientation;
  6094. (function (Orientation) {
  6095. Orientation[Orientation["CW"] = 0] = "CW";
  6096. Orientation[Orientation["CCW"] = 1] = "CCW";
  6097. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6098. var Angle = /** @class */ (function () {
  6099. /**
  6100. * Creates an Angle object of "radians" radians (float).
  6101. */
  6102. function Angle(radians) {
  6103. var _this = this;
  6104. /**
  6105. * Returns the Angle value in degrees (float).
  6106. */
  6107. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6108. /**
  6109. * Returns the Angle value in radians (float).
  6110. */
  6111. this.radians = function () { return _this._radians; };
  6112. this._radians = radians;
  6113. if (this._radians < 0.0)
  6114. this._radians += (2.0 * Math.PI);
  6115. }
  6116. /**
  6117. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6118. */
  6119. Angle.BetweenTwoPoints = function (a, b) {
  6120. var delta = b.subtract(a);
  6121. var theta = Math.atan2(delta.y, delta.x);
  6122. return new Angle(theta);
  6123. };
  6124. /**
  6125. * Returns a new Angle object from the passed float in radians.
  6126. */
  6127. Angle.FromRadians = function (radians) {
  6128. return new Angle(radians);
  6129. };
  6130. /**
  6131. * Returns a new Angle object from the passed float in degrees.
  6132. */
  6133. Angle.FromDegrees = function (degrees) {
  6134. return new Angle(degrees * Math.PI / 180.0);
  6135. };
  6136. return Angle;
  6137. }());
  6138. BABYLON.Angle = Angle;
  6139. var Arc2 = /** @class */ (function () {
  6140. /**
  6141. * Creates an Arc object from the three passed points : start, middle and end.
  6142. */
  6143. function Arc2(startPoint, midPoint, endPoint) {
  6144. this.startPoint = startPoint;
  6145. this.midPoint = midPoint;
  6146. this.endPoint = endPoint;
  6147. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6148. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6149. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6150. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6151. 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);
  6152. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6153. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6154. var a1 = this.startAngle.degrees();
  6155. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6156. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6157. // angles correction
  6158. if (a2 - a1 > +180.0)
  6159. a2 -= 360.0;
  6160. if (a2 - a1 < -180.0)
  6161. a2 += 360.0;
  6162. if (a3 - a2 > +180.0)
  6163. a3 -= 360.0;
  6164. if (a3 - a2 < -180.0)
  6165. a3 += 360.0;
  6166. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6167. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6168. }
  6169. return Arc2;
  6170. }());
  6171. BABYLON.Arc2 = Arc2;
  6172. var Path2 = /** @class */ (function () {
  6173. /**
  6174. * Creates a Path2 object from the starting 2D coordinates x and y.
  6175. */
  6176. function Path2(x, y) {
  6177. this._points = new Array();
  6178. this._length = 0.0;
  6179. this.closed = false;
  6180. this._points.push(new Vector2(x, y));
  6181. }
  6182. /**
  6183. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6184. * Returns the updated Path2.
  6185. */
  6186. Path2.prototype.addLineTo = function (x, y) {
  6187. if (this.closed) {
  6188. return this;
  6189. }
  6190. var newPoint = new Vector2(x, y);
  6191. var previousPoint = this._points[this._points.length - 1];
  6192. this._points.push(newPoint);
  6193. this._length += newPoint.subtract(previousPoint).length();
  6194. return this;
  6195. };
  6196. /**
  6197. * 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.
  6198. * Returns the updated Path2.
  6199. */
  6200. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6201. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6202. if (this.closed) {
  6203. return this;
  6204. }
  6205. var startPoint = this._points[this._points.length - 1];
  6206. var midPoint = new Vector2(midX, midY);
  6207. var endPoint = new Vector2(endX, endY);
  6208. var arc = new Arc2(startPoint, midPoint, endPoint);
  6209. var increment = arc.angle.radians() / numberOfSegments;
  6210. if (arc.orientation === Orientation.CW)
  6211. increment *= -1;
  6212. var currentAngle = arc.startAngle.radians() + increment;
  6213. for (var i = 0; i < numberOfSegments; i++) {
  6214. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6215. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6216. this.addLineTo(x, y);
  6217. currentAngle += increment;
  6218. }
  6219. return this;
  6220. };
  6221. /**
  6222. * Closes the Path2.
  6223. * Returns the Path2.
  6224. */
  6225. Path2.prototype.close = function () {
  6226. this.closed = true;
  6227. return this;
  6228. };
  6229. /**
  6230. * Returns the Path2 total length (float).
  6231. */
  6232. Path2.prototype.length = function () {
  6233. var result = this._length;
  6234. if (!this.closed) {
  6235. var lastPoint = this._points[this._points.length - 1];
  6236. var firstPoint = this._points[0];
  6237. result += (firstPoint.subtract(lastPoint).length());
  6238. }
  6239. return result;
  6240. };
  6241. /**
  6242. * Returns the Path2 internal array of points.
  6243. */
  6244. Path2.prototype.getPoints = function () {
  6245. return this._points;
  6246. };
  6247. /**
  6248. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6249. */
  6250. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6251. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6252. return Vector2.Zero();
  6253. }
  6254. var lengthPosition = normalizedLengthPosition * this.length();
  6255. var previousOffset = 0;
  6256. for (var i = 0; i < this._points.length; i++) {
  6257. var j = (i + 1) % this._points.length;
  6258. var a = this._points[i];
  6259. var b = this._points[j];
  6260. var bToA = b.subtract(a);
  6261. var nextOffset = (bToA.length() + previousOffset);
  6262. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6263. var dir = bToA.normalize();
  6264. var localOffset = lengthPosition - previousOffset;
  6265. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6266. }
  6267. previousOffset = nextOffset;
  6268. }
  6269. return Vector2.Zero();
  6270. };
  6271. /**
  6272. * Returns a new Path2 starting at the coordinates (x, y).
  6273. */
  6274. Path2.StartingAt = function (x, y) {
  6275. return new Path2(x, y);
  6276. };
  6277. return Path2;
  6278. }());
  6279. BABYLON.Path2 = Path2;
  6280. var Path3D = /** @class */ (function () {
  6281. /**
  6282. * new Path3D(path, normal, raw)
  6283. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6284. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6285. * path : an array of Vector3, the curve axis of the Path3D
  6286. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6287. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6288. */
  6289. function Path3D(path, firstNormal, raw) {
  6290. if (firstNormal === void 0) { firstNormal = null; }
  6291. this.path = path;
  6292. this._curve = new Array();
  6293. this._distances = new Array();
  6294. this._tangents = new Array();
  6295. this._normals = new Array();
  6296. this._binormals = new Array();
  6297. for (var p = 0; p < path.length; p++) {
  6298. this._curve[p] = path[p].clone(); // hard copy
  6299. }
  6300. this._raw = raw || false;
  6301. this._compute(firstNormal);
  6302. }
  6303. /**
  6304. * Returns the Path3D array of successive Vector3 designing its curve.
  6305. */
  6306. Path3D.prototype.getCurve = function () {
  6307. return this._curve;
  6308. };
  6309. /**
  6310. * Returns an array populated with tangent vectors on each Path3D curve point.
  6311. */
  6312. Path3D.prototype.getTangents = function () {
  6313. return this._tangents;
  6314. };
  6315. /**
  6316. * Returns an array populated with normal vectors on each Path3D curve point.
  6317. */
  6318. Path3D.prototype.getNormals = function () {
  6319. return this._normals;
  6320. };
  6321. /**
  6322. * Returns an array populated with binormal vectors on each Path3D curve point.
  6323. */
  6324. Path3D.prototype.getBinormals = function () {
  6325. return this._binormals;
  6326. };
  6327. /**
  6328. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6329. */
  6330. Path3D.prototype.getDistances = function () {
  6331. return this._distances;
  6332. };
  6333. /**
  6334. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6335. * Returns the same object updated.
  6336. */
  6337. Path3D.prototype.update = function (path, firstNormal) {
  6338. if (firstNormal === void 0) { firstNormal = null; }
  6339. for (var p = 0; p < path.length; p++) {
  6340. this._curve[p].x = path[p].x;
  6341. this._curve[p].y = path[p].y;
  6342. this._curve[p].z = path[p].z;
  6343. }
  6344. this._compute(firstNormal);
  6345. return this;
  6346. };
  6347. // private function compute() : computes tangents, normals and binormals
  6348. Path3D.prototype._compute = function (firstNormal) {
  6349. var l = this._curve.length;
  6350. // first and last tangents
  6351. this._tangents[0] = this._getFirstNonNullVector(0);
  6352. if (!this._raw) {
  6353. this._tangents[0].normalize();
  6354. }
  6355. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6356. if (!this._raw) {
  6357. this._tangents[l - 1].normalize();
  6358. }
  6359. // normals and binormals at first point : arbitrary vector with _normalVector()
  6360. var tg0 = this._tangents[0];
  6361. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6362. this._normals[0] = pp0;
  6363. if (!this._raw) {
  6364. this._normals[0].normalize();
  6365. }
  6366. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6367. if (!this._raw) {
  6368. this._binormals[0].normalize();
  6369. }
  6370. this._distances[0] = 0.0;
  6371. // normals and binormals : next points
  6372. var prev; // previous vector (segment)
  6373. var cur; // current vector (segment)
  6374. var curTang; // current tangent
  6375. // previous normal
  6376. var prevBinor; // previous binormal
  6377. for (var i = 1; i < l; i++) {
  6378. // tangents
  6379. prev = this._getLastNonNullVector(i);
  6380. if (i < l - 1) {
  6381. cur = this._getFirstNonNullVector(i);
  6382. this._tangents[i] = prev.add(cur);
  6383. this._tangents[i].normalize();
  6384. }
  6385. this._distances[i] = this._distances[i - 1] + prev.length();
  6386. // normals and binormals
  6387. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6388. curTang = this._tangents[i];
  6389. prevBinor = this._binormals[i - 1];
  6390. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6391. if (!this._raw) {
  6392. this._normals[i].normalize();
  6393. }
  6394. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6395. if (!this._raw) {
  6396. this._binormals[i].normalize();
  6397. }
  6398. }
  6399. };
  6400. // private function getFirstNonNullVector(index)
  6401. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6402. Path3D.prototype._getFirstNonNullVector = function (index) {
  6403. var i = 1;
  6404. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6405. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6406. i++;
  6407. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6408. }
  6409. return nNVector;
  6410. };
  6411. // private function getLastNonNullVector(index)
  6412. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6413. Path3D.prototype._getLastNonNullVector = function (index) {
  6414. var i = 1;
  6415. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6416. while (nLVector.length() === 0 && index > i + 1) {
  6417. i++;
  6418. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6419. }
  6420. return nLVector;
  6421. };
  6422. // private function normalVector(v0, vt, va) :
  6423. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6424. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6425. Path3D.prototype._normalVector = function (v0, vt, va) {
  6426. var normal0;
  6427. var tgl = vt.length();
  6428. if (tgl === 0.0) {
  6429. tgl = 1.0;
  6430. }
  6431. if (va === undefined || va === null) {
  6432. var point;
  6433. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6434. point = new Vector3(0.0, -1.0, 0.0);
  6435. }
  6436. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6437. point = new Vector3(1.0, 0.0, 0.0);
  6438. }
  6439. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6440. point = new Vector3(0.0, 0.0, 1.0);
  6441. }
  6442. else {
  6443. point = Vector3.Zero();
  6444. }
  6445. normal0 = Vector3.Cross(vt, point);
  6446. }
  6447. else {
  6448. normal0 = Vector3.Cross(vt, va);
  6449. Vector3.CrossToRef(normal0, vt, normal0);
  6450. }
  6451. normal0.normalize();
  6452. return normal0;
  6453. };
  6454. return Path3D;
  6455. }());
  6456. BABYLON.Path3D = Path3D;
  6457. var Curve3 = /** @class */ (function () {
  6458. /**
  6459. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6460. * A Curve3 is designed from a series of successive Vector3.
  6461. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6462. */
  6463. function Curve3(points) {
  6464. this._length = 0.0;
  6465. this._points = points;
  6466. this._length = this._computeLength(points);
  6467. }
  6468. /**
  6469. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6470. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6471. * @param v1 (Vector3) the control point
  6472. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6473. * @param nbPoints (integer) the wanted number of points in the curve
  6474. */
  6475. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6476. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6477. var bez = new Array();
  6478. var equation = function (t, val0, val1, val2) {
  6479. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6480. return res;
  6481. };
  6482. for (var i = 0; i <= nbPoints; i++) {
  6483. 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)));
  6484. }
  6485. return new Curve3(bez);
  6486. };
  6487. /**
  6488. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6489. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6490. * @param v1 (Vector3) the first control point
  6491. * @param v2 (Vector3) the second control point
  6492. * @param v3 (Vector3) the end point of the Cubic Bezier
  6493. * @param nbPoints (integer) the wanted number of points in the curve
  6494. */
  6495. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6496. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6497. var bez = new Array();
  6498. var equation = function (t, val0, val1, val2, val3) {
  6499. 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;
  6500. return res;
  6501. };
  6502. for (var i = 0; i <= nbPoints; i++) {
  6503. 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)));
  6504. }
  6505. return new Curve3(bez);
  6506. };
  6507. /**
  6508. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6509. * @param p1 (Vector3) the origin point of the Hermite Spline
  6510. * @param t1 (Vector3) the tangent vector at the origin point
  6511. * @param p2 (Vector3) the end point of the Hermite Spline
  6512. * @param t2 (Vector3) the tangent vector at the end point
  6513. * @param nbPoints (integer) the wanted number of points in the curve
  6514. */
  6515. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6516. var hermite = new Array();
  6517. var step = 1.0 / nbPoints;
  6518. for (var i = 0; i <= nbPoints; i++) {
  6519. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6520. }
  6521. return new Curve3(hermite);
  6522. };
  6523. /**
  6524. * Returns a Curve3 object along a CatmullRom Spline curve :
  6525. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6526. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6527. */
  6528. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6529. var totalPoints = new Array();
  6530. totalPoints.push(points[0].clone());
  6531. Array.prototype.push.apply(totalPoints, points);
  6532. totalPoints.push(points[points.length - 1].clone());
  6533. var catmullRom = new Array();
  6534. var step = 1.0 / nbPoints;
  6535. var amount = 0.0;
  6536. for (var i = 0; i < totalPoints.length - 3; i++) {
  6537. amount = 0;
  6538. for (var c = 0; c < nbPoints; c++) {
  6539. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6540. amount += step;
  6541. }
  6542. }
  6543. i--;
  6544. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6545. return new Curve3(catmullRom);
  6546. };
  6547. /**
  6548. * Returns the Curve3 stored array of successive Vector3
  6549. */
  6550. Curve3.prototype.getPoints = function () {
  6551. return this._points;
  6552. };
  6553. /**
  6554. * Returns the computed length (float) of the curve.
  6555. */
  6556. Curve3.prototype.length = function () {
  6557. return this._length;
  6558. };
  6559. /**
  6560. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6561. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6562. * curveA and curveB keep unchanged.
  6563. */
  6564. Curve3.prototype.continue = function (curve) {
  6565. var lastPoint = this._points[this._points.length - 1];
  6566. var continuedPoints = this._points.slice();
  6567. var curvePoints = curve.getPoints();
  6568. for (var i = 1; i < curvePoints.length; i++) {
  6569. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6570. }
  6571. var continuedCurve = new Curve3(continuedPoints);
  6572. return continuedCurve;
  6573. };
  6574. Curve3.prototype._computeLength = function (path) {
  6575. var l = 0;
  6576. for (var i = 1; i < path.length; i++) {
  6577. l += (path[i].subtract(path[i - 1])).length();
  6578. }
  6579. return l;
  6580. };
  6581. return Curve3;
  6582. }());
  6583. BABYLON.Curve3 = Curve3;
  6584. // Vertex formats
  6585. var PositionNormalVertex = /** @class */ (function () {
  6586. function PositionNormalVertex(position, normal) {
  6587. if (position === void 0) { position = Vector3.Zero(); }
  6588. if (normal === void 0) { normal = Vector3.Up(); }
  6589. this.position = position;
  6590. this.normal = normal;
  6591. }
  6592. PositionNormalVertex.prototype.clone = function () {
  6593. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6594. };
  6595. return PositionNormalVertex;
  6596. }());
  6597. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6598. var PositionNormalTextureVertex = /** @class */ (function () {
  6599. function PositionNormalTextureVertex(position, normal, uv) {
  6600. if (position === void 0) { position = Vector3.Zero(); }
  6601. if (normal === void 0) { normal = Vector3.Up(); }
  6602. if (uv === void 0) { uv = Vector2.Zero(); }
  6603. this.position = position;
  6604. this.normal = normal;
  6605. this.uv = uv;
  6606. }
  6607. PositionNormalTextureVertex.prototype.clone = function () {
  6608. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6609. };
  6610. return PositionNormalTextureVertex;
  6611. }());
  6612. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6613. // Temporary pre-allocated objects for engine internal use
  6614. // usage in any internal function :
  6615. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6616. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6617. var Tmp = /** @class */ (function () {
  6618. function Tmp() {
  6619. }
  6620. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6621. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6622. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6623. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6624. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6625. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6626. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6627. Matrix.Zero(), Matrix.Zero(),
  6628. Matrix.Zero(), Matrix.Zero(),
  6629. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6630. return Tmp;
  6631. }());
  6632. BABYLON.Tmp = Tmp;
  6633. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6634. var MathTmp = /** @class */ (function () {
  6635. function MathTmp() {
  6636. }
  6637. MathTmp.Vector3 = [Vector3.Zero()];
  6638. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6639. MathTmp.Quaternion = [Quaternion.Zero()];
  6640. return MathTmp;
  6641. }());
  6642. })(BABYLON || (BABYLON = {}));
  6643. //# sourceMappingURL=babylon.math.js.map
  6644. var BABYLON;
  6645. (function (BABYLON) {
  6646. var Scalar = /** @class */ (function () {
  6647. function Scalar() {
  6648. }
  6649. /**
  6650. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6651. */
  6652. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6653. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6654. var num = a - b;
  6655. return -epsilon <= num && num <= epsilon;
  6656. };
  6657. /**
  6658. * Returns a string : the upper case translation of the number i to hexadecimal.
  6659. */
  6660. Scalar.ToHex = function (i) {
  6661. var str = i.toString(16);
  6662. if (i <= 15) {
  6663. return ("0" + str).toUpperCase();
  6664. }
  6665. return str.toUpperCase();
  6666. };
  6667. /**
  6668. * Returns -1 if value is negative and +1 is value is positive.
  6669. * Returns the value itself if it's equal to zero.
  6670. */
  6671. Scalar.Sign = function (value) {
  6672. value = +value; // convert to a number
  6673. if (value === 0 || isNaN(value))
  6674. return value;
  6675. return value > 0 ? 1 : -1;
  6676. };
  6677. /**
  6678. * Returns the value itself if it's between min and max.
  6679. * Returns min if the value is lower than min.
  6680. * Returns max if the value is greater than max.
  6681. */
  6682. Scalar.Clamp = function (value, min, max) {
  6683. if (min === void 0) { min = 0; }
  6684. if (max === void 0) { max = 1; }
  6685. return Math.min(max, Math.max(min, value));
  6686. };
  6687. /**
  6688. * Returns the log2 of value.
  6689. */
  6690. Scalar.Log2 = function (value) {
  6691. return Math.log(value) * Math.LOG2E;
  6692. };
  6693. /**
  6694. * Loops the value, so that it is never larger than length and never smaller than 0.
  6695. *
  6696. * This is similar to the modulo operator but it works with floating point numbers.
  6697. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6698. * With t = 5 and length = 2.5, the result would be 0.0.
  6699. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6700. */
  6701. Scalar.Repeat = function (value, length) {
  6702. return value - Math.floor(value / length) * length;
  6703. };
  6704. /**
  6705. * Normalize the value between 0.0 and 1.0 using min and max values
  6706. */
  6707. Scalar.Normalize = function (value, min, max) {
  6708. return (value - min) / (max - min);
  6709. };
  6710. /**
  6711. * Denormalize the value from 0.0 and 1.0 using min and max values
  6712. */
  6713. Scalar.Denormalize = function (normalized, min, max) {
  6714. return (normalized * (max - min) + min);
  6715. };
  6716. /**
  6717. * Calculates the shortest difference between two given angles given in degrees.
  6718. */
  6719. Scalar.DeltaAngle = function (current, target) {
  6720. var num = Scalar.Repeat(target - current, 360.0);
  6721. if (num > 180.0) {
  6722. num -= 360.0;
  6723. }
  6724. return num;
  6725. };
  6726. /**
  6727. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6728. *
  6729. * The returned value will move back and forth between 0 and length
  6730. */
  6731. Scalar.PingPong = function (tx, length) {
  6732. var t = Scalar.Repeat(tx, length * 2.0);
  6733. return length - Math.abs(t - length);
  6734. };
  6735. /**
  6736. * Interpolates between min and max with smoothing at the limits.
  6737. *
  6738. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6739. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6740. */
  6741. Scalar.SmoothStep = function (from, to, tx) {
  6742. var t = Scalar.Clamp(tx);
  6743. t = -2.0 * t * t * t + 3.0 * t * t;
  6744. return to * t + from * (1.0 - t);
  6745. };
  6746. /**
  6747. * Moves a value current towards target.
  6748. *
  6749. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6750. * Negative values of maxDelta pushes the value away from target.
  6751. */
  6752. Scalar.MoveTowards = function (current, target, maxDelta) {
  6753. var result = 0;
  6754. if (Math.abs(target - current) <= maxDelta) {
  6755. result = target;
  6756. }
  6757. else {
  6758. result = current + Scalar.Sign(target - current) * maxDelta;
  6759. }
  6760. return result;
  6761. };
  6762. /**
  6763. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6764. *
  6765. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6766. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6767. */
  6768. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6769. var num = Scalar.DeltaAngle(current, target);
  6770. var result = 0;
  6771. if (-maxDelta < num && num < maxDelta) {
  6772. result = target;
  6773. }
  6774. else {
  6775. target = current + num;
  6776. result = Scalar.MoveTowards(current, target, maxDelta);
  6777. }
  6778. return result;
  6779. };
  6780. /**
  6781. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6782. */
  6783. Scalar.Lerp = function (start, end, amount) {
  6784. return start + ((end - start) * amount);
  6785. };
  6786. /**
  6787. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6788. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6789. */
  6790. Scalar.LerpAngle = function (start, end, amount) {
  6791. var num = Scalar.Repeat(end - start, 360.0);
  6792. if (num > 180.0) {
  6793. num -= 360.0;
  6794. }
  6795. return start + num * Scalar.Clamp(amount);
  6796. };
  6797. /**
  6798. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6799. */
  6800. Scalar.InverseLerp = function (a, b, value) {
  6801. var result = 0;
  6802. if (a != b) {
  6803. result = Scalar.Clamp((value - a) / (b - a));
  6804. }
  6805. else {
  6806. result = 0.0;
  6807. }
  6808. return result;
  6809. };
  6810. /**
  6811. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6812. */
  6813. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6814. var squared = amount * amount;
  6815. var cubed = amount * squared;
  6816. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6817. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6818. var part3 = (cubed - (2.0 * squared)) + amount;
  6819. var part4 = cubed - squared;
  6820. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6821. };
  6822. /**
  6823. * Returns a random float number between and min and max values
  6824. */
  6825. Scalar.RandomRange = function (min, max) {
  6826. if (min === max)
  6827. return min;
  6828. return ((Math.random() * (max - min)) + min);
  6829. };
  6830. /**
  6831. * This function returns percentage of a number in a given range.
  6832. *
  6833. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6834. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6835. */
  6836. Scalar.RangeToPercent = function (number, min, max) {
  6837. return ((number - min) / (max - min));
  6838. };
  6839. /**
  6840. * This function returns number that corresponds to the percentage in a given range.
  6841. *
  6842. * PercentToRange(0.34,0,100) will return 34.
  6843. */
  6844. Scalar.PercentToRange = function (percent, min, max) {
  6845. return ((max - min) * percent + min);
  6846. };
  6847. /**
  6848. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6849. * @param angle The angle to normalize in radian.
  6850. * @return The converted angle.
  6851. */
  6852. Scalar.NormalizeRadians = function (angle) {
  6853. // More precise but slower version kept for reference.
  6854. // angle = angle % Tools.TwoPi;
  6855. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6856. //if (angle > Math.PI) {
  6857. // angle -= Tools.TwoPi;
  6858. //}
  6859. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6860. return angle;
  6861. };
  6862. /**
  6863. * Two pi constants convenient for computation.
  6864. */
  6865. Scalar.TwoPi = Math.PI * 2;
  6866. return Scalar;
  6867. }());
  6868. BABYLON.Scalar = Scalar;
  6869. })(BABYLON || (BABYLON = {}));
  6870. //# sourceMappingURL=babylon.math.scalar.js.map
  6871. //# sourceMappingURL=babylon.mixins.js.map
  6872. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6873. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6874. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6875. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6876. //# sourceMappingURL=babylon.webgl2.js.map
  6877. var BABYLON;
  6878. (function (BABYLON) {
  6879. var __decoratorInitialStore = {};
  6880. var __mergedStore = {};
  6881. var _copySource = function (creationFunction, source, instanciate) {
  6882. var destination = creationFunction();
  6883. // Tags
  6884. if (BABYLON.Tags) {
  6885. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6886. }
  6887. var classStore = getMergedStore(destination);
  6888. // Properties
  6889. for (var property in classStore) {
  6890. var propertyDescriptor = classStore[property];
  6891. var sourceProperty = source[property];
  6892. var propertyType = propertyDescriptor.type;
  6893. if (sourceProperty !== undefined && sourceProperty !== null) {
  6894. switch (propertyType) {
  6895. case 0: // Value
  6896. case 6:// Mesh reference
  6897. destination[property] = sourceProperty;
  6898. break;
  6899. case 1:// Texture
  6900. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6901. break;
  6902. case 2: // Color3
  6903. case 3: // FresnelParameters
  6904. case 4: // Vector2
  6905. case 5: // Vector3
  6906. case 7: // Color Curves
  6907. case 10:// Quaternion
  6908. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6909. break;
  6910. }
  6911. }
  6912. }
  6913. return destination;
  6914. };
  6915. function getDirectStore(target) {
  6916. var classKey = target.getClassName();
  6917. if (!__decoratorInitialStore[classKey]) {
  6918. __decoratorInitialStore[classKey] = {};
  6919. }
  6920. return __decoratorInitialStore[classKey];
  6921. }
  6922. /**
  6923. * Return the list of properties flagged as serializable
  6924. * @param target: host object
  6925. */
  6926. function getMergedStore(target) {
  6927. var classKey = target.getClassName();
  6928. if (__mergedStore[classKey]) {
  6929. return __mergedStore[classKey];
  6930. }
  6931. __mergedStore[classKey] = {};
  6932. var store = __mergedStore[classKey];
  6933. var currentTarget = target;
  6934. var currentKey = classKey;
  6935. while (currentKey) {
  6936. var initialStore = __decoratorInitialStore[currentKey];
  6937. for (var property in initialStore) {
  6938. store[property] = initialStore[property];
  6939. }
  6940. var parent_1 = void 0;
  6941. var done = false;
  6942. do {
  6943. parent_1 = Object.getPrototypeOf(currentTarget);
  6944. if (!parent_1.getClassName) {
  6945. done = true;
  6946. break;
  6947. }
  6948. if (parent_1.getClassName() !== currentKey) {
  6949. break;
  6950. }
  6951. currentTarget = parent_1;
  6952. } while (parent_1);
  6953. if (done) {
  6954. break;
  6955. }
  6956. currentKey = parent_1.getClassName();
  6957. currentTarget = parent_1;
  6958. }
  6959. return store;
  6960. }
  6961. function generateSerializableMember(type, sourceName) {
  6962. return function (target, propertyKey) {
  6963. var classStore = getDirectStore(target);
  6964. if (!classStore[propertyKey]) {
  6965. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6966. }
  6967. };
  6968. }
  6969. function generateExpandMember(setCallback, targetKey) {
  6970. if (targetKey === void 0) { targetKey = null; }
  6971. return function (target, propertyKey) {
  6972. var key = targetKey || ("_" + propertyKey);
  6973. Object.defineProperty(target, propertyKey, {
  6974. get: function () {
  6975. return this[key];
  6976. },
  6977. set: function (value) {
  6978. if (this[key] === value) {
  6979. return;
  6980. }
  6981. this[key] = value;
  6982. target[setCallback].apply(this);
  6983. },
  6984. enumerable: true,
  6985. configurable: true
  6986. });
  6987. };
  6988. }
  6989. function expandToProperty(callback, targetKey) {
  6990. if (targetKey === void 0) { targetKey = null; }
  6991. return generateExpandMember(callback, targetKey);
  6992. }
  6993. BABYLON.expandToProperty = expandToProperty;
  6994. function serialize(sourceName) {
  6995. return generateSerializableMember(0, sourceName); // value member
  6996. }
  6997. BABYLON.serialize = serialize;
  6998. function serializeAsTexture(sourceName) {
  6999. return generateSerializableMember(1, sourceName); // texture member
  7000. }
  7001. BABYLON.serializeAsTexture = serializeAsTexture;
  7002. function serializeAsColor3(sourceName) {
  7003. return generateSerializableMember(2, sourceName); // color3 member
  7004. }
  7005. BABYLON.serializeAsColor3 = serializeAsColor3;
  7006. function serializeAsFresnelParameters(sourceName) {
  7007. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7008. }
  7009. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7010. function serializeAsVector2(sourceName) {
  7011. return generateSerializableMember(4, sourceName); // vector2 member
  7012. }
  7013. BABYLON.serializeAsVector2 = serializeAsVector2;
  7014. function serializeAsVector3(sourceName) {
  7015. return generateSerializableMember(5, sourceName); // vector3 member
  7016. }
  7017. BABYLON.serializeAsVector3 = serializeAsVector3;
  7018. function serializeAsMeshReference(sourceName) {
  7019. return generateSerializableMember(6, sourceName); // mesh reference member
  7020. }
  7021. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7022. function serializeAsColorCurves(sourceName) {
  7023. return generateSerializableMember(7, sourceName); // color curves
  7024. }
  7025. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7026. function serializeAsColor4(sourceName) {
  7027. return generateSerializableMember(8, sourceName); // color 4
  7028. }
  7029. BABYLON.serializeAsColor4 = serializeAsColor4;
  7030. function serializeAsImageProcessingConfiguration(sourceName) {
  7031. return generateSerializableMember(9, sourceName); // image processing
  7032. }
  7033. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7034. function serializeAsQuaternion(sourceName) {
  7035. return generateSerializableMember(10, sourceName); // quaternion member
  7036. }
  7037. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7038. var SerializationHelper = /** @class */ (function () {
  7039. function SerializationHelper() {
  7040. }
  7041. SerializationHelper.Serialize = function (entity, serializationObject) {
  7042. if (!serializationObject) {
  7043. serializationObject = {};
  7044. }
  7045. // Tags
  7046. if (BABYLON.Tags) {
  7047. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7048. }
  7049. var serializedProperties = getMergedStore(entity);
  7050. // Properties
  7051. for (var property in serializedProperties) {
  7052. var propertyDescriptor = serializedProperties[property];
  7053. var targetPropertyName = propertyDescriptor.sourceName || property;
  7054. var propertyType = propertyDescriptor.type;
  7055. var sourceProperty = entity[property];
  7056. if (sourceProperty !== undefined && sourceProperty !== null) {
  7057. switch (propertyType) {
  7058. case 0:// Value
  7059. serializationObject[targetPropertyName] = sourceProperty;
  7060. break;
  7061. case 1:// Texture
  7062. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7063. break;
  7064. case 2:// Color3
  7065. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7066. break;
  7067. case 3:// FresnelParameters
  7068. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7069. break;
  7070. case 4:// Vector2
  7071. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7072. break;
  7073. case 5:// Vector3
  7074. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7075. break;
  7076. case 6:// Mesh reference
  7077. serializationObject[targetPropertyName] = sourceProperty.id;
  7078. break;
  7079. case 7:// Color Curves
  7080. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7081. break;
  7082. case 8:// Color 4
  7083. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7084. break;
  7085. case 9:// Image Processing
  7086. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7087. break;
  7088. }
  7089. }
  7090. }
  7091. return serializationObject;
  7092. };
  7093. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7094. if (rootUrl === void 0) { rootUrl = null; }
  7095. var destination = creationFunction();
  7096. if (!rootUrl) {
  7097. rootUrl = "";
  7098. }
  7099. // Tags
  7100. if (BABYLON.Tags) {
  7101. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7102. }
  7103. var classStore = getMergedStore(destination);
  7104. // Properties
  7105. for (var property in classStore) {
  7106. var propertyDescriptor = classStore[property];
  7107. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7108. var propertyType = propertyDescriptor.type;
  7109. if (sourceProperty !== undefined && sourceProperty !== null) {
  7110. var dest = destination;
  7111. switch (propertyType) {
  7112. case 0:// Value
  7113. dest[property] = sourceProperty;
  7114. break;
  7115. case 1:// Texture
  7116. if (scene) {
  7117. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7118. }
  7119. break;
  7120. case 2:// Color3
  7121. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7122. break;
  7123. case 3:// FresnelParameters
  7124. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7125. break;
  7126. case 4:// Vector2
  7127. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7128. break;
  7129. case 5:// Vector3
  7130. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7131. break;
  7132. case 6:// Mesh reference
  7133. if (scene) {
  7134. dest[property] = scene.getLastMeshByID(sourceProperty);
  7135. }
  7136. break;
  7137. case 7:// Color Curves
  7138. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7139. break;
  7140. case 8:// Color 4
  7141. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7142. break;
  7143. case 9:// Image Processing
  7144. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7145. break;
  7146. }
  7147. }
  7148. }
  7149. return destination;
  7150. };
  7151. SerializationHelper.Clone = function (creationFunction, source) {
  7152. return _copySource(creationFunction, source, false);
  7153. };
  7154. SerializationHelper.Instanciate = function (creationFunction, source) {
  7155. return _copySource(creationFunction, source, true);
  7156. };
  7157. return SerializationHelper;
  7158. }());
  7159. BABYLON.SerializationHelper = SerializationHelper;
  7160. })(BABYLON || (BABYLON = {}));
  7161. //# sourceMappingURL=babylon.decorators.js.map
  7162. var BABYLON;
  7163. (function (BABYLON) {
  7164. /**
  7165. * Wrapper class for promise with external resolve and reject.
  7166. */
  7167. var Deferred = /** @class */ (function () {
  7168. /**
  7169. * Constructor for this deferred object.
  7170. */
  7171. function Deferred() {
  7172. var _this = this;
  7173. this.promise = new Promise(function (resolve, reject) {
  7174. _this._resolve = resolve;
  7175. _this._reject = reject;
  7176. });
  7177. }
  7178. Object.defineProperty(Deferred.prototype, "resolve", {
  7179. /**
  7180. * The resolve method of the promise associated with this deferred object.
  7181. */
  7182. get: function () {
  7183. return this._resolve;
  7184. },
  7185. enumerable: true,
  7186. configurable: true
  7187. });
  7188. Object.defineProperty(Deferred.prototype, "reject", {
  7189. /**
  7190. * The reject method of the promise associated with this deferred object.
  7191. */
  7192. get: function () {
  7193. return this._reject;
  7194. },
  7195. enumerable: true,
  7196. configurable: true
  7197. });
  7198. return Deferred;
  7199. }());
  7200. BABYLON.Deferred = Deferred;
  7201. })(BABYLON || (BABYLON = {}));
  7202. //# sourceMappingURL=babylon.deferred.js.map
  7203. var BABYLON;
  7204. (function (BABYLON) {
  7205. /**
  7206. * A class serves as a medium between the observable and its observers
  7207. */
  7208. var EventState = /** @class */ (function () {
  7209. /**
  7210. * Create a new EventState
  7211. * @param mask defines the mask associated with this state
  7212. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7213. * @param target defines the original target of the state
  7214. * @param currentTarget defines the current target of the state
  7215. */
  7216. function EventState(mask, skipNextObservers, target, currentTarget) {
  7217. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7218. this.initalize(mask, skipNextObservers, target, currentTarget);
  7219. }
  7220. /**
  7221. * Initialize the current event state
  7222. * @param mask defines the mask associated with this state
  7223. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7224. * @param target defines the original target of the state
  7225. * @param currentTarget defines the current target of the state
  7226. * @returns the current event state
  7227. */
  7228. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7229. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7230. this.mask = mask;
  7231. this.skipNextObservers = skipNextObservers;
  7232. this.target = target;
  7233. this.currentTarget = currentTarget;
  7234. return this;
  7235. };
  7236. return EventState;
  7237. }());
  7238. BABYLON.EventState = EventState;
  7239. /**
  7240. * Represent an Observer registered to a given Observable object.
  7241. */
  7242. var Observer = /** @class */ (function () {
  7243. /**
  7244. * Creates a new observer
  7245. * @param callback defines the callback to call when the observer is notified
  7246. * @param mask defines the mask of the observer (used to filter notifications)
  7247. * @param scope defines the current scope used to restore the JS context
  7248. */
  7249. function Observer(
  7250. /**
  7251. * Defines the callback to call when the observer is notified
  7252. */
  7253. callback,
  7254. /**
  7255. * Defines the mask of the observer (used to filter notifications)
  7256. */
  7257. mask,
  7258. /**
  7259. * Defines the current scope used to restore the JS context
  7260. */
  7261. scope) {
  7262. if (scope === void 0) { scope = null; }
  7263. this.callback = callback;
  7264. this.mask = mask;
  7265. this.scope = scope;
  7266. /** @ignore */
  7267. this._willBeUnregistered = false;
  7268. /**
  7269. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7270. */
  7271. this.unregisterOnNextCall = false;
  7272. }
  7273. return Observer;
  7274. }());
  7275. BABYLON.Observer = Observer;
  7276. /**
  7277. * Represent a list of observers registered to multiple Observables object.
  7278. */
  7279. var MultiObserver = /** @class */ (function () {
  7280. function MultiObserver() {
  7281. }
  7282. /**
  7283. * Release associated resources
  7284. */
  7285. MultiObserver.prototype.dispose = function () {
  7286. if (this._observers && this._observables) {
  7287. for (var index = 0; index < this._observers.length; index++) {
  7288. this._observables[index].remove(this._observers[index]);
  7289. }
  7290. }
  7291. this._observers = null;
  7292. this._observables = null;
  7293. };
  7294. /**
  7295. * Raise a callback when one of the observable will notify
  7296. * @param observables defines a list of observables to watch
  7297. * @param callback defines the callback to call on notification
  7298. * @param mask defines the mask used to filter notifications
  7299. * @param scope defines the current scope used to restore the JS context
  7300. * @returns the new MultiObserver
  7301. */
  7302. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7303. if (mask === void 0) { mask = -1; }
  7304. if (scope === void 0) { scope = null; }
  7305. var result = new MultiObserver();
  7306. result._observers = new Array();
  7307. result._observables = observables;
  7308. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7309. var observable = observables_1[_i];
  7310. var observer = observable.add(callback, mask, false, scope);
  7311. if (observer) {
  7312. result._observers.push(observer);
  7313. }
  7314. }
  7315. return result;
  7316. };
  7317. return MultiObserver;
  7318. }());
  7319. BABYLON.MultiObserver = MultiObserver;
  7320. /**
  7321. * The Observable class is a simple implementation of the Observable pattern.
  7322. * 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.
  7323. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7324. * 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).
  7325. * 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.
  7326. */
  7327. var Observable = /** @class */ (function () {
  7328. /**
  7329. * Creates a new observable
  7330. * @param onObserverAdded defines a callback to call when a new observer is added
  7331. */
  7332. function Observable(onObserverAdded) {
  7333. this._observers = new Array();
  7334. this._eventState = new EventState(0);
  7335. if (onObserverAdded) {
  7336. this._onObserverAdded = onObserverAdded;
  7337. }
  7338. }
  7339. /**
  7340. * Create a new Observer with the specified callback
  7341. * @param callback the callback that will be executed for that Observer
  7342. * @param mask the mask used to filter observers
  7343. * @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.
  7344. * @param scope optional scope for the callback to be called from
  7345. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7346. * @returns the new observer created for the callback
  7347. */
  7348. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7349. if (mask === void 0) { mask = -1; }
  7350. if (insertFirst === void 0) { insertFirst = false; }
  7351. if (scope === void 0) { scope = null; }
  7352. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7353. if (!callback) {
  7354. return null;
  7355. }
  7356. var observer = new Observer(callback, mask, scope);
  7357. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7358. if (insertFirst) {
  7359. this._observers.unshift(observer);
  7360. }
  7361. else {
  7362. this._observers.push(observer);
  7363. }
  7364. if (this._onObserverAdded) {
  7365. this._onObserverAdded(observer);
  7366. }
  7367. return observer;
  7368. };
  7369. /**
  7370. * Remove an Observer from the Observable object
  7371. * @param observer the instance of the Observer to remove
  7372. * @returns false if it doesn't belong to this Observable
  7373. */
  7374. Observable.prototype.remove = function (observer) {
  7375. if (!observer) {
  7376. return false;
  7377. }
  7378. var index = this._observers.indexOf(observer);
  7379. if (index !== -1) {
  7380. this._observers.splice(index, 1);
  7381. return true;
  7382. }
  7383. return false;
  7384. };
  7385. /**
  7386. * Remove a callback from the Observable object
  7387. * @param callback the callback to remove
  7388. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7389. * @returns false if it doesn't belong to this Observable
  7390. */
  7391. Observable.prototype.removeCallback = function (callback, scope) {
  7392. for (var index = 0; index < this._observers.length; index++) {
  7393. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7394. this._observers.splice(index, 1);
  7395. return true;
  7396. }
  7397. }
  7398. return false;
  7399. };
  7400. Observable.prototype._deferUnregister = function (observer) {
  7401. var _this = this;
  7402. observer.unregisterOnNextCall = false;
  7403. observer._willBeUnregistered = true;
  7404. BABYLON.Tools.SetImmediate(function () {
  7405. _this.remove(observer);
  7406. });
  7407. };
  7408. /**
  7409. * Notify all Observers by calling their respective callback with the given data
  7410. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7411. * @param eventData defines the data to send to all observers
  7412. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7413. * @param target defines the original target of the state
  7414. * @param currentTarget defines the current target of the state
  7415. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7416. */
  7417. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7418. if (mask === void 0) { mask = -1; }
  7419. if (!this._observers.length) {
  7420. return true;
  7421. }
  7422. var state = this._eventState;
  7423. state.mask = mask;
  7424. state.target = target;
  7425. state.currentTarget = currentTarget;
  7426. state.skipNextObservers = false;
  7427. state.lastReturnValue = eventData;
  7428. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7429. var obs = _a[_i];
  7430. if (obs._willBeUnregistered) {
  7431. continue;
  7432. }
  7433. if (obs.mask & mask) {
  7434. if (obs.scope) {
  7435. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7436. }
  7437. else {
  7438. state.lastReturnValue = obs.callback(eventData, state);
  7439. }
  7440. if (obs.unregisterOnNextCall) {
  7441. this._deferUnregister(obs);
  7442. }
  7443. }
  7444. if (state.skipNextObservers) {
  7445. return false;
  7446. }
  7447. }
  7448. return true;
  7449. };
  7450. /**
  7451. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7452. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7453. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7454. * and it is crucial that all callbacks will be executed.
  7455. * The order of the callbacks is kept, callbacks are not executed parallel.
  7456. *
  7457. * @param eventData The data to be sent to each callback
  7458. * @param mask is used to filter observers defaults to -1
  7459. * @param target defines the callback target (see EventState)
  7460. * @param currentTarget defines he current object in the bubbling phase
  7461. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7462. */
  7463. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7464. var _this = this;
  7465. if (mask === void 0) { mask = -1; }
  7466. // create an empty promise
  7467. var p = Promise.resolve(eventData);
  7468. // no observers? return this promise.
  7469. if (!this._observers.length) {
  7470. return p;
  7471. }
  7472. var state = this._eventState;
  7473. state.mask = mask;
  7474. state.target = target;
  7475. state.currentTarget = currentTarget;
  7476. state.skipNextObservers = false;
  7477. // execute one callback after another (not using Promise.all, the order is important)
  7478. this._observers.forEach(function (obs) {
  7479. if (state.skipNextObservers) {
  7480. return;
  7481. }
  7482. if (obs._willBeUnregistered) {
  7483. return;
  7484. }
  7485. if (obs.mask & mask) {
  7486. if (obs.scope) {
  7487. p = p.then(function (lastReturnedValue) {
  7488. state.lastReturnValue = lastReturnedValue;
  7489. return obs.callback.apply(obs.scope, [eventData, state]);
  7490. });
  7491. }
  7492. else {
  7493. p = p.then(function (lastReturnedValue) {
  7494. state.lastReturnValue = lastReturnedValue;
  7495. return obs.callback(eventData, state);
  7496. });
  7497. }
  7498. if (obs.unregisterOnNextCall) {
  7499. _this._deferUnregister(obs);
  7500. }
  7501. }
  7502. });
  7503. // return the eventData
  7504. return p.then(function () { return eventData; });
  7505. };
  7506. /**
  7507. * Notify a specific observer
  7508. * @param observer defines the observer to notify
  7509. * @param eventData defines the data to be sent to each callback
  7510. * @param mask is used to filter observers defaults to -1
  7511. */
  7512. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7513. if (mask === void 0) { mask = -1; }
  7514. var state = this._eventState;
  7515. state.mask = mask;
  7516. state.skipNextObservers = false;
  7517. observer.callback(eventData, state);
  7518. };
  7519. /**
  7520. * Gets a boolean indicating if the observable has at least one observer
  7521. * @returns true is the Observable has at least one Observer registered
  7522. */
  7523. Observable.prototype.hasObservers = function () {
  7524. return this._observers.length > 0;
  7525. };
  7526. /**
  7527. * Clear the list of observers
  7528. */
  7529. Observable.prototype.clear = function () {
  7530. this._observers = new Array();
  7531. this._onObserverAdded = null;
  7532. };
  7533. /**
  7534. * Clone the current observable
  7535. * @returns a new observable
  7536. */
  7537. Observable.prototype.clone = function () {
  7538. var result = new Observable();
  7539. result._observers = this._observers.slice(0);
  7540. return result;
  7541. };
  7542. /**
  7543. * Does this observable handles observer registered with a given mask
  7544. * @param mask defines the mask to be tested
  7545. * @return whether or not one observer registered with the given mask is handeled
  7546. **/
  7547. Observable.prototype.hasSpecificMask = function (mask) {
  7548. if (mask === void 0) { mask = -1; }
  7549. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7550. var obs = _a[_i];
  7551. if (obs.mask & mask || obs.mask === mask) {
  7552. return true;
  7553. }
  7554. }
  7555. return false;
  7556. };
  7557. return Observable;
  7558. }());
  7559. BABYLON.Observable = Observable;
  7560. })(BABYLON || (BABYLON = {}));
  7561. //# sourceMappingURL=babylon.observable.js.map
  7562. var BABYLON;
  7563. (function (BABYLON) {
  7564. var SmartArray = /** @class */ (function () {
  7565. function SmartArray(capacity) {
  7566. this.length = 0;
  7567. this.data = new Array(capacity);
  7568. this._id = SmartArray._GlobalId++;
  7569. }
  7570. SmartArray.prototype.push = function (value) {
  7571. this.data[this.length++] = value;
  7572. if (this.length > this.data.length) {
  7573. this.data.length *= 2;
  7574. }
  7575. };
  7576. SmartArray.prototype.forEach = function (func) {
  7577. for (var index = 0; index < this.length; index++) {
  7578. func(this.data[index]);
  7579. }
  7580. };
  7581. SmartArray.prototype.sort = function (compareFn) {
  7582. this.data.sort(compareFn);
  7583. };
  7584. SmartArray.prototype.reset = function () {
  7585. this.length = 0;
  7586. };
  7587. SmartArray.prototype.dispose = function () {
  7588. this.reset();
  7589. if (this.data) {
  7590. this.data.length = 0;
  7591. this.data = [];
  7592. }
  7593. };
  7594. SmartArray.prototype.concat = function (array) {
  7595. if (array.length === 0) {
  7596. return;
  7597. }
  7598. if (this.length + array.length > this.data.length) {
  7599. this.data.length = (this.length + array.length) * 2;
  7600. }
  7601. for (var index = 0; index < array.length; index++) {
  7602. this.data[this.length++] = (array.data || array)[index];
  7603. }
  7604. };
  7605. SmartArray.prototype.indexOf = function (value) {
  7606. var position = this.data.indexOf(value);
  7607. if (position >= this.length) {
  7608. return -1;
  7609. }
  7610. return position;
  7611. };
  7612. SmartArray.prototype.contains = function (value) {
  7613. return this.data.indexOf(value) !== -1;
  7614. };
  7615. // Statics
  7616. SmartArray._GlobalId = 0;
  7617. return SmartArray;
  7618. }());
  7619. BABYLON.SmartArray = SmartArray;
  7620. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7621. __extends(SmartArrayNoDuplicate, _super);
  7622. function SmartArrayNoDuplicate() {
  7623. var _this = _super !== null && _super.apply(this, arguments) || this;
  7624. _this._duplicateId = 0;
  7625. return _this;
  7626. }
  7627. SmartArrayNoDuplicate.prototype.push = function (value) {
  7628. _super.prototype.push.call(this, value);
  7629. if (!value.__smartArrayFlags) {
  7630. value.__smartArrayFlags = {};
  7631. }
  7632. value.__smartArrayFlags[this._id] = this._duplicateId;
  7633. };
  7634. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7635. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7636. return false;
  7637. }
  7638. this.push(value);
  7639. return true;
  7640. };
  7641. SmartArrayNoDuplicate.prototype.reset = function () {
  7642. _super.prototype.reset.call(this);
  7643. this._duplicateId++;
  7644. };
  7645. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7646. if (array.length === 0) {
  7647. return;
  7648. }
  7649. if (this.length + array.length > this.data.length) {
  7650. this.data.length = (this.length + array.length) * 2;
  7651. }
  7652. for (var index = 0; index < array.length; index++) {
  7653. var item = (array.data || array)[index];
  7654. this.pushNoDuplicate(item);
  7655. }
  7656. };
  7657. return SmartArrayNoDuplicate;
  7658. }(SmartArray));
  7659. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7660. })(BABYLON || (BABYLON = {}));
  7661. //# sourceMappingURL=babylon.smartArray.js.map
  7662. var BABYLON;
  7663. (function (BABYLON) {
  7664. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7665. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7666. var LoadFileError = /** @class */ (function (_super) {
  7667. __extends(LoadFileError, _super);
  7668. function LoadFileError(message, request) {
  7669. var _this = _super.call(this, message) || this;
  7670. _this.request = request;
  7671. _this.name = "LoadFileError";
  7672. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7673. return _this;
  7674. }
  7675. // Polyfill for Object.setPrototypeOf if necessary.
  7676. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7677. return LoadFileError;
  7678. }(Error));
  7679. BABYLON.LoadFileError = LoadFileError;
  7680. var RetryStrategy = /** @class */ (function () {
  7681. function RetryStrategy() {
  7682. }
  7683. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7684. if (maxRetries === void 0) { maxRetries = 3; }
  7685. if (baseInterval === void 0) { baseInterval = 500; }
  7686. return function (url, request, retryIndex) {
  7687. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7688. return -1;
  7689. }
  7690. return Math.pow(2, retryIndex) * baseInterval;
  7691. };
  7692. };
  7693. return RetryStrategy;
  7694. }());
  7695. BABYLON.RetryStrategy = RetryStrategy;
  7696. // Screenshots
  7697. var screenshotCanvas;
  7698. var cloneValue = function (source, destinationObject) {
  7699. if (!source)
  7700. return null;
  7701. if (source instanceof BABYLON.Mesh) {
  7702. return null;
  7703. }
  7704. if (source instanceof BABYLON.SubMesh) {
  7705. return source.clone(destinationObject);
  7706. }
  7707. else if (source.clone) {
  7708. return source.clone();
  7709. }
  7710. return null;
  7711. };
  7712. var Tools = /** @class */ (function () {
  7713. function Tools() {
  7714. }
  7715. /**
  7716. * Interpolates between a and b via alpha
  7717. * @param a The lower value (returned when alpha = 0)
  7718. * @param b The upper value (returned when alpha = 1)
  7719. * @param alpha The interpolation-factor
  7720. * @return The mixed value
  7721. */
  7722. Tools.Mix = function (a, b, alpha) {
  7723. return a * (1 - alpha) + b * alpha;
  7724. };
  7725. Tools.Instantiate = function (className) {
  7726. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7727. return Tools.RegisteredExternalClasses[className];
  7728. }
  7729. var arr = className.split(".");
  7730. var fn = (window || this);
  7731. for (var i = 0, len = arr.length; i < len; i++) {
  7732. fn = fn[arr[i]];
  7733. }
  7734. if (typeof fn !== "function") {
  7735. return null;
  7736. }
  7737. return fn;
  7738. };
  7739. /**
  7740. * Provides a slice function that will work even on IE
  7741. * @param data defines the array to slice
  7742. * @returns the new sliced array
  7743. */
  7744. Tools.Slice = function (data) {
  7745. if (data.slice) {
  7746. return data.slice();
  7747. }
  7748. return Array.prototype.slice.call(data);
  7749. };
  7750. Tools.SetImmediate = function (action) {
  7751. if (window.setImmediate) {
  7752. window.setImmediate(action);
  7753. }
  7754. else {
  7755. setTimeout(action, 1);
  7756. }
  7757. };
  7758. Tools.IsExponentOfTwo = function (value) {
  7759. var count = 1;
  7760. do {
  7761. count *= 2;
  7762. } while (count < value);
  7763. return count === value;
  7764. };
  7765. /**
  7766. * Find the next highest power of two.
  7767. * @param x Number to start search from.
  7768. * @return Next highest power of two.
  7769. */
  7770. Tools.CeilingPOT = function (x) {
  7771. x--;
  7772. x |= x >> 1;
  7773. x |= x >> 2;
  7774. x |= x >> 4;
  7775. x |= x >> 8;
  7776. x |= x >> 16;
  7777. x++;
  7778. return x;
  7779. };
  7780. /**
  7781. * Find the next lowest power of two.
  7782. * @param x Number to start search from.
  7783. * @return Next lowest power of two.
  7784. */
  7785. Tools.FloorPOT = function (x) {
  7786. x = x | (x >> 1);
  7787. x = x | (x >> 2);
  7788. x = x | (x >> 4);
  7789. x = x | (x >> 8);
  7790. x = x | (x >> 16);
  7791. return x - (x >> 1);
  7792. };
  7793. /**
  7794. * Find the nearest power of two.
  7795. * @param x Number to start search from.
  7796. * @return Next nearest power of two.
  7797. */
  7798. Tools.NearestPOT = function (x) {
  7799. var c = Tools.CeilingPOT(x);
  7800. var f = Tools.FloorPOT(x);
  7801. return (c - x) > (x - f) ? f : c;
  7802. };
  7803. Tools.GetExponentOfTwo = function (value, max, mode) {
  7804. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7805. var pot;
  7806. switch (mode) {
  7807. case BABYLON.Engine.SCALEMODE_FLOOR:
  7808. pot = Tools.FloorPOT(value);
  7809. break;
  7810. case BABYLON.Engine.SCALEMODE_NEAREST:
  7811. pot = Tools.NearestPOT(value);
  7812. break;
  7813. case BABYLON.Engine.SCALEMODE_CEILING:
  7814. default:
  7815. pot = Tools.CeilingPOT(value);
  7816. break;
  7817. }
  7818. return Math.min(pot, max);
  7819. };
  7820. Tools.GetFilename = function (path) {
  7821. var index = path.lastIndexOf("/");
  7822. if (index < 0)
  7823. return path;
  7824. return path.substring(index + 1);
  7825. };
  7826. /**
  7827. * Extracts the "folder" part of a path (everything before the filename).
  7828. * @param uri The URI to extract the info from
  7829. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7830. * @returns The "folder" part of the path
  7831. */
  7832. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  7833. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  7834. var index = uri.lastIndexOf("/");
  7835. if (index < 0) {
  7836. if (returnUnchangedIfNoSlash) {
  7837. return uri;
  7838. }
  7839. return "";
  7840. }
  7841. return uri.substring(0, index + 1);
  7842. };
  7843. Tools.GetDOMTextContent = function (element) {
  7844. var result = "";
  7845. var child = element.firstChild;
  7846. while (child) {
  7847. if (child.nodeType === 3) {
  7848. result += child.textContent;
  7849. }
  7850. child = child.nextSibling;
  7851. }
  7852. return result;
  7853. };
  7854. Tools.ToDegrees = function (angle) {
  7855. return angle * 180 / Math.PI;
  7856. };
  7857. Tools.ToRadians = function (angle) {
  7858. return angle * Math.PI / 180;
  7859. };
  7860. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  7861. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  7862. var output = "";
  7863. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  7864. var i = 0;
  7865. var bytes = new Uint8Array(buffer);
  7866. while (i < bytes.length) {
  7867. chr1 = bytes[i++];
  7868. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  7869. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  7870. enc1 = chr1 >> 2;
  7871. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  7872. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  7873. enc4 = chr3 & 63;
  7874. if (isNaN(chr2)) {
  7875. enc3 = enc4 = 64;
  7876. }
  7877. else if (isNaN(chr3)) {
  7878. enc4 = 64;
  7879. }
  7880. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  7881. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  7882. }
  7883. return "data:image/png;base64," + output;
  7884. };
  7885. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  7886. if (bias === void 0) { bias = null; }
  7887. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7888. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7889. for (var index = indexStart; index < indexStart + indexCount; index++) {
  7890. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  7891. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7892. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7893. }
  7894. if (bias) {
  7895. minimum.x -= minimum.x * bias.x + bias.y;
  7896. minimum.y -= minimum.y * bias.x + bias.y;
  7897. minimum.z -= minimum.z * bias.x + bias.y;
  7898. maximum.x += maximum.x * bias.x + bias.y;
  7899. maximum.y += maximum.y * bias.x + bias.y;
  7900. maximum.z += maximum.z * bias.x + bias.y;
  7901. }
  7902. return {
  7903. minimum: minimum,
  7904. maximum: maximum
  7905. };
  7906. };
  7907. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  7908. if (bias === void 0) { bias = null; }
  7909. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7910. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7911. if (!stride) {
  7912. stride = 3;
  7913. }
  7914. for (var index = start; index < start + count; index++) {
  7915. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  7916. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7917. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7918. }
  7919. if (bias) {
  7920. minimum.x -= minimum.x * bias.x + bias.y;
  7921. minimum.y -= minimum.y * bias.x + bias.y;
  7922. minimum.z -= minimum.z * bias.x + bias.y;
  7923. maximum.x += maximum.x * bias.x + bias.y;
  7924. maximum.y += maximum.y * bias.x + bias.y;
  7925. maximum.z += maximum.z * bias.x + bias.y;
  7926. }
  7927. return {
  7928. minimum: minimum,
  7929. maximum: maximum
  7930. };
  7931. };
  7932. Tools.Vector2ArrayFeeder = function (array) {
  7933. return function (index) {
  7934. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  7935. var length = isFloatArray ? array.length / 2 : array.length;
  7936. if (index >= length) {
  7937. return null;
  7938. }
  7939. if (isFloatArray) {
  7940. var fa = array;
  7941. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  7942. }
  7943. var a = array;
  7944. return a[index];
  7945. };
  7946. };
  7947. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  7948. if (bias === void 0) { bias = null; }
  7949. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  7950. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  7951. var i = 0;
  7952. var cur = feeder(i++);
  7953. while (cur) {
  7954. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  7955. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  7956. cur = feeder(i++);
  7957. }
  7958. if (bias) {
  7959. minimum.x -= minimum.x * bias.x + bias.y;
  7960. minimum.y -= minimum.y * bias.x + bias.y;
  7961. maximum.x += maximum.x * bias.x + bias.y;
  7962. maximum.y += maximum.y * bias.x + bias.y;
  7963. }
  7964. return {
  7965. minimum: minimum,
  7966. maximum: maximum
  7967. };
  7968. };
  7969. Tools.MakeArray = function (obj, allowsNullUndefined) {
  7970. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  7971. return null;
  7972. return Array.isArray(obj) ? obj : [obj];
  7973. };
  7974. // Misc.
  7975. Tools.GetPointerPrefix = function () {
  7976. var eventPrefix = "pointer";
  7977. // Check if pointer events are supported
  7978. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  7979. eventPrefix = "mouse";
  7980. }
  7981. return eventPrefix;
  7982. };
  7983. /**
  7984. * @param func - the function to be called
  7985. * @param requester - the object that will request the next frame. Falls back to window.
  7986. */
  7987. Tools.QueueNewFrame = function (func, requester) {
  7988. if (!Tools.IsWindowObjectExist()) {
  7989. return setTimeout(func, 16);
  7990. }
  7991. if (!requester) {
  7992. requester = window;
  7993. }
  7994. if (requester.requestAnimationFrame) {
  7995. return requester.requestAnimationFrame(func);
  7996. }
  7997. else if (requester.msRequestAnimationFrame) {
  7998. return requester.msRequestAnimationFrame(func);
  7999. }
  8000. else if (requester.webkitRequestAnimationFrame) {
  8001. return requester.webkitRequestAnimationFrame(func);
  8002. }
  8003. else if (requester.mozRequestAnimationFrame) {
  8004. return requester.mozRequestAnimationFrame(func);
  8005. }
  8006. else if (requester.oRequestAnimationFrame) {
  8007. return requester.oRequestAnimationFrame(func);
  8008. }
  8009. else {
  8010. return window.setTimeout(func, 16);
  8011. }
  8012. };
  8013. Tools.RequestFullscreen = function (element) {
  8014. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8015. if (!requestFunction)
  8016. return;
  8017. requestFunction.call(element);
  8018. };
  8019. Tools.ExitFullscreen = function () {
  8020. if (document.exitFullscreen) {
  8021. document.exitFullscreen();
  8022. }
  8023. else if (document.mozCancelFullScreen) {
  8024. document.mozCancelFullScreen();
  8025. }
  8026. else if (document.webkitCancelFullScreen) {
  8027. document.webkitCancelFullScreen();
  8028. }
  8029. else if (document.msCancelFullScreen) {
  8030. document.msCancelFullScreen();
  8031. }
  8032. };
  8033. Tools.SetCorsBehavior = function (url, element) {
  8034. if (url && url.indexOf("data:") === 0) {
  8035. return;
  8036. }
  8037. if (Tools.CorsBehavior) {
  8038. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8039. element.crossOrigin = Tools.CorsBehavior;
  8040. }
  8041. else {
  8042. var result = Tools.CorsBehavior(url);
  8043. if (result) {
  8044. element.crossOrigin = result;
  8045. }
  8046. }
  8047. }
  8048. };
  8049. // External files
  8050. Tools.CleanUrl = function (url) {
  8051. url = url.replace(/#/mg, "%23");
  8052. return url;
  8053. };
  8054. Tools.LoadImage = function (url, onLoad, onError, database) {
  8055. if (url instanceof ArrayBuffer) {
  8056. url = Tools.EncodeArrayBufferTobase64(url);
  8057. }
  8058. url = Tools.CleanUrl(url);
  8059. url = Tools.PreprocessUrl(url);
  8060. var img = new Image();
  8061. Tools.SetCorsBehavior(url, img);
  8062. var loadHandler = function () {
  8063. img.removeEventListener("load", loadHandler);
  8064. img.removeEventListener("error", errorHandler);
  8065. onLoad(img);
  8066. };
  8067. var errorHandler = function (err) {
  8068. img.removeEventListener("load", loadHandler);
  8069. img.removeEventListener("error", errorHandler);
  8070. Tools.Error("Error while trying to load image: " + url);
  8071. if (onError) {
  8072. onError("Error while trying to load image: " + url, err);
  8073. }
  8074. };
  8075. img.addEventListener("load", loadHandler);
  8076. img.addEventListener("error", errorHandler);
  8077. var noIndexedDB = function () {
  8078. img.src = url;
  8079. };
  8080. var loadFromIndexedDB = function () {
  8081. if (database) {
  8082. database.loadImageFromDB(url, img);
  8083. }
  8084. };
  8085. //ANY database to do!
  8086. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8087. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8088. }
  8089. else {
  8090. if (url.indexOf("file:") !== -1) {
  8091. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8092. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8093. try {
  8094. var blobURL;
  8095. try {
  8096. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8097. }
  8098. catch (ex) {
  8099. // Chrome doesn't support oneTimeOnly parameter
  8100. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8101. }
  8102. img.src = blobURL;
  8103. }
  8104. catch (e) {
  8105. img.src = "";
  8106. }
  8107. return img;
  8108. }
  8109. }
  8110. noIndexedDB();
  8111. }
  8112. return img;
  8113. };
  8114. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8115. url = Tools.CleanUrl(url);
  8116. url = Tools.PreprocessUrl(url);
  8117. // If file and file input are set
  8118. if (url.indexOf("file:") !== -1) {
  8119. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8120. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8121. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8122. }
  8123. }
  8124. var loadUrl = Tools.BaseUrl + url;
  8125. var aborted = false;
  8126. var fileRequest = {
  8127. onCompleteObservable: new BABYLON.Observable(),
  8128. abort: function () { return aborted = true; },
  8129. };
  8130. var requestFile = function () {
  8131. var request = new XMLHttpRequest();
  8132. var retryHandle = null;
  8133. fileRequest.abort = function () {
  8134. aborted = true;
  8135. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8136. request.abort();
  8137. }
  8138. if (retryHandle !== null) {
  8139. clearTimeout(retryHandle);
  8140. retryHandle = null;
  8141. }
  8142. };
  8143. var retryLoop = function (retryIndex) {
  8144. request.open('GET', loadUrl, true);
  8145. if (useArrayBuffer) {
  8146. request.responseType = "arraybuffer";
  8147. }
  8148. if (onProgress) {
  8149. request.addEventListener("progress", onProgress);
  8150. }
  8151. var onLoadEnd = function () {
  8152. request.removeEventListener("loadend", onLoadEnd);
  8153. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8154. fileRequest.onCompleteObservable.clear();
  8155. };
  8156. request.addEventListener("loadend", onLoadEnd);
  8157. var onReadyStateChange = function () {
  8158. if (aborted) {
  8159. return;
  8160. }
  8161. // In case of undefined state in some browsers.
  8162. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8163. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8164. request.removeEventListener("readystatechange", onReadyStateChange);
  8165. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8166. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8167. return;
  8168. }
  8169. var retryStrategy = Tools.DefaultRetryStrategy;
  8170. if (retryStrategy) {
  8171. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8172. if (waitTime !== -1) {
  8173. // Prevent the request from completing for retry.
  8174. request.removeEventListener("loadend", onLoadEnd);
  8175. request = new XMLHttpRequest();
  8176. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8177. return;
  8178. }
  8179. }
  8180. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8181. if (onError) {
  8182. onError(request, e);
  8183. }
  8184. else {
  8185. throw e;
  8186. }
  8187. }
  8188. };
  8189. request.addEventListener("readystatechange", onReadyStateChange);
  8190. request.send();
  8191. };
  8192. retryLoop(0);
  8193. };
  8194. // Caching all files
  8195. if (database && database.enableSceneOffline) {
  8196. var noIndexedDB_1 = function () {
  8197. if (!aborted) {
  8198. requestFile();
  8199. }
  8200. };
  8201. var loadFromIndexedDB = function () {
  8202. // TODO: database needs to support aborting and should return a IFileRequest
  8203. if (aborted) {
  8204. return;
  8205. }
  8206. if (database) {
  8207. database.loadFileFromDB(url, function (data) {
  8208. if (!aborted) {
  8209. onSuccess(data);
  8210. }
  8211. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8212. }, onProgress ? function (event) {
  8213. if (!aborted) {
  8214. onProgress(event);
  8215. }
  8216. } : undefined, noIndexedDB_1, useArrayBuffer);
  8217. }
  8218. };
  8219. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8220. }
  8221. else {
  8222. requestFile();
  8223. }
  8224. return fileRequest;
  8225. };
  8226. /**
  8227. * Load a script (identified by an url). When the url returns, the
  8228. * content of this file is added into a new script element, attached to the DOM (body element)
  8229. */
  8230. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8231. var head = document.getElementsByTagName('head')[0];
  8232. var script = document.createElement('script');
  8233. script.type = 'text/javascript';
  8234. script.src = scriptUrl;
  8235. script.onload = function () {
  8236. if (onSuccess) {
  8237. onSuccess();
  8238. }
  8239. };
  8240. script.onerror = function (e) {
  8241. if (onError) {
  8242. onError("Unable to load script", e);
  8243. }
  8244. };
  8245. head.appendChild(script);
  8246. };
  8247. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8248. var reader = new FileReader();
  8249. var request = {
  8250. onCompleteObservable: new BABYLON.Observable(),
  8251. abort: function () { return reader.abort(); },
  8252. };
  8253. reader.onloadend = function (e) {
  8254. request.onCompleteObservable.notifyObservers(request);
  8255. };
  8256. reader.onload = function (e) {
  8257. //target doesn't have result from ts 1.3
  8258. callback(e.target['result']);
  8259. };
  8260. reader.onprogress = progressCallback;
  8261. reader.readAsDataURL(fileToLoad);
  8262. return request;
  8263. };
  8264. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8265. var reader = new FileReader();
  8266. var request = {
  8267. onCompleteObservable: new BABYLON.Observable(),
  8268. abort: function () { return reader.abort(); },
  8269. };
  8270. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8271. reader.onerror = function (e) {
  8272. Tools.Log("Error while reading file: " + fileToLoad.name);
  8273. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8274. };
  8275. reader.onload = function (e) {
  8276. //target doesn't have result from ts 1.3
  8277. callback(e.target['result']);
  8278. };
  8279. if (progressCallBack) {
  8280. reader.onprogress = progressCallBack;
  8281. }
  8282. if (!useArrayBuffer) {
  8283. // Asynchronous read
  8284. reader.readAsText(fileToLoad);
  8285. }
  8286. else {
  8287. reader.readAsArrayBuffer(fileToLoad);
  8288. }
  8289. return request;
  8290. };
  8291. //returns a downloadable url to a file content.
  8292. Tools.FileAsURL = function (content) {
  8293. var fileBlob = new Blob([content]);
  8294. var url = window.URL || window.webkitURL;
  8295. var link = url.createObjectURL(fileBlob);
  8296. return link;
  8297. };
  8298. // Misc.
  8299. Tools.Format = function (value, decimals) {
  8300. if (decimals === void 0) { decimals = 2; }
  8301. return value.toFixed(decimals);
  8302. };
  8303. Tools.CheckExtends = function (v, min, max) {
  8304. if (v.x < min.x)
  8305. min.x = v.x;
  8306. if (v.y < min.y)
  8307. min.y = v.y;
  8308. if (v.z < min.z)
  8309. min.z = v.z;
  8310. if (v.x > max.x)
  8311. max.x = v.x;
  8312. if (v.y > max.y)
  8313. max.y = v.y;
  8314. if (v.z > max.z)
  8315. max.z = v.z;
  8316. };
  8317. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8318. for (var prop in source) {
  8319. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8320. continue;
  8321. }
  8322. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8323. continue;
  8324. }
  8325. var sourceValue = source[prop];
  8326. var typeOfSourceValue = typeof sourceValue;
  8327. if (typeOfSourceValue === "function") {
  8328. continue;
  8329. }
  8330. if (typeOfSourceValue === "object") {
  8331. if (sourceValue instanceof Array) {
  8332. destination[prop] = [];
  8333. if (sourceValue.length > 0) {
  8334. if (typeof sourceValue[0] == "object") {
  8335. for (var index = 0; index < sourceValue.length; index++) {
  8336. var clonedValue = cloneValue(sourceValue[index], destination);
  8337. if (destination[prop].indexOf(clonedValue) === -1) {
  8338. destination[prop].push(clonedValue);
  8339. }
  8340. }
  8341. }
  8342. else {
  8343. destination[prop] = sourceValue.slice(0);
  8344. }
  8345. }
  8346. }
  8347. else {
  8348. destination[prop] = cloneValue(sourceValue, destination);
  8349. }
  8350. }
  8351. else {
  8352. destination[prop] = sourceValue;
  8353. }
  8354. }
  8355. };
  8356. Tools.IsEmpty = function (obj) {
  8357. for (var i in obj) {
  8358. if (obj.hasOwnProperty(i)) {
  8359. return false;
  8360. }
  8361. }
  8362. return true;
  8363. };
  8364. Tools.RegisterTopRootEvents = function (events) {
  8365. for (var index = 0; index < events.length; index++) {
  8366. var event = events[index];
  8367. window.addEventListener(event.name, event.handler, false);
  8368. try {
  8369. if (window.parent) {
  8370. window.parent.addEventListener(event.name, event.handler, false);
  8371. }
  8372. }
  8373. catch (e) {
  8374. // Silently fails...
  8375. }
  8376. }
  8377. };
  8378. Tools.UnregisterTopRootEvents = function (events) {
  8379. for (var index = 0; index < events.length; index++) {
  8380. var event = events[index];
  8381. window.removeEventListener(event.name, event.handler);
  8382. try {
  8383. if (window.parent) {
  8384. window.parent.removeEventListener(event.name, event.handler);
  8385. }
  8386. }
  8387. catch (e) {
  8388. // Silently fails...
  8389. }
  8390. }
  8391. };
  8392. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8393. if (mimeType === void 0) { mimeType = "image/png"; }
  8394. // Read the contents of the framebuffer
  8395. var numberOfChannelsByLine = width * 4;
  8396. var halfHeight = height / 2;
  8397. //Reading datas from WebGL
  8398. var data = engine.readPixels(0, 0, width, height);
  8399. //To flip image on Y axis.
  8400. for (var i = 0; i < halfHeight; i++) {
  8401. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8402. var currentCell = j + i * numberOfChannelsByLine;
  8403. var targetLine = height - i - 1;
  8404. var targetCell = j + targetLine * numberOfChannelsByLine;
  8405. var temp = data[currentCell];
  8406. data[currentCell] = data[targetCell];
  8407. data[targetCell] = temp;
  8408. }
  8409. }
  8410. // Create a 2D canvas to store the result
  8411. if (!screenshotCanvas) {
  8412. screenshotCanvas = document.createElement('canvas');
  8413. }
  8414. screenshotCanvas.width = width;
  8415. screenshotCanvas.height = height;
  8416. var context = screenshotCanvas.getContext('2d');
  8417. if (context) {
  8418. // Copy the pixels to a 2D canvas
  8419. var imageData = context.createImageData(width, height);
  8420. var castData = (imageData.data);
  8421. castData.set(data);
  8422. context.putImageData(imageData, 0, 0);
  8423. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8424. }
  8425. };
  8426. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8427. if (mimeType === void 0) { mimeType = "image/png"; }
  8428. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8429. if (successCallback) {
  8430. successCallback(base64Image);
  8431. }
  8432. else {
  8433. // We need HTMLCanvasElement.toBlob for HD screenshots
  8434. if (!screenshotCanvas.toBlob) {
  8435. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8436. screenshotCanvas.toBlob = function (callback, type, quality) {
  8437. var _this = this;
  8438. setTimeout(function () {
  8439. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8440. for (var i = 0; i < len; i++) {
  8441. arr[i] = binStr.charCodeAt(i);
  8442. }
  8443. callback(new Blob([arr], { type: type || 'image/png' }));
  8444. });
  8445. };
  8446. }
  8447. screenshotCanvas.toBlob(function (blob) {
  8448. var url = URL.createObjectURL(blob);
  8449. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8450. if (("download" in document.createElement("a"))) {
  8451. var a = window.document.createElement("a");
  8452. a.href = url;
  8453. if (fileName) {
  8454. a.setAttribute("download", fileName);
  8455. }
  8456. else {
  8457. var date = new Date();
  8458. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8459. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8460. }
  8461. window.document.body.appendChild(a);
  8462. a.addEventListener("click", function () {
  8463. if (a.parentElement) {
  8464. a.parentElement.removeChild(a);
  8465. }
  8466. });
  8467. a.click();
  8468. }
  8469. else {
  8470. var newWindow = window.open("");
  8471. if (!newWindow)
  8472. return;
  8473. var img = newWindow.document.createElement("img");
  8474. img.onload = function () {
  8475. // no longer need to read the blob so it's revoked
  8476. URL.revokeObjectURL(url);
  8477. };
  8478. img.src = url;
  8479. newWindow.document.body.appendChild(img);
  8480. }
  8481. });
  8482. }
  8483. };
  8484. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8485. if (mimeType === void 0) { mimeType = "image/png"; }
  8486. var width;
  8487. var height;
  8488. // If a precision value is specified
  8489. if (size.precision) {
  8490. width = Math.round(engine.getRenderWidth() * size.precision);
  8491. height = Math.round(width / engine.getAspectRatio(camera));
  8492. }
  8493. else if (size.width && size.height) {
  8494. width = size.width;
  8495. height = size.height;
  8496. }
  8497. else if (size.width && !size.height) {
  8498. width = size.width;
  8499. height = Math.round(width / engine.getAspectRatio(camera));
  8500. }
  8501. else if (size.height && !size.width) {
  8502. height = size.height;
  8503. width = Math.round(height * engine.getAspectRatio(camera));
  8504. }
  8505. else if (!isNaN(size)) {
  8506. height = size;
  8507. width = size;
  8508. }
  8509. else {
  8510. Tools.Error("Invalid 'size' parameter !");
  8511. return;
  8512. }
  8513. if (!screenshotCanvas) {
  8514. screenshotCanvas = document.createElement('canvas');
  8515. }
  8516. screenshotCanvas.width = width;
  8517. screenshotCanvas.height = height;
  8518. var renderContext = screenshotCanvas.getContext("2d");
  8519. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8520. var newWidth = width;
  8521. var newHeight = newWidth / ratio;
  8522. if (newHeight > height) {
  8523. newHeight = height;
  8524. newWidth = newHeight * ratio;
  8525. }
  8526. var offsetX = Math.max(0, width - newWidth) / 2;
  8527. var offsetY = Math.max(0, height - newHeight) / 2;
  8528. var renderingCanvas = engine.getRenderingCanvas();
  8529. if (renderContext && renderingCanvas) {
  8530. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8531. }
  8532. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8533. };
  8534. /**
  8535. * Generates an image screenshot from the specified camera.
  8536. *
  8537. * @param engine The engine to use for rendering
  8538. * @param camera The camera to use for rendering
  8539. * @param size This parameter can be set to a single number or to an object with the
  8540. * following (optional) properties: precision, width, height. If a single number is passed,
  8541. * it will be used for both width and height. If an object is passed, the screenshot size
  8542. * will be derived from the parameters. The precision property is a multiplier allowing
  8543. * rendering at a higher or lower resolution.
  8544. * @param successCallback The callback receives a single parameter which contains the
  8545. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8546. * src parameter of an <img> to display it.
  8547. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8548. * Check your browser for supported MIME types.
  8549. * @param samples Texture samples (default: 1)
  8550. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8551. * @param fileName A name for for the downloaded file.
  8552. * @constructor
  8553. */
  8554. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8555. if (mimeType === void 0) { mimeType = "image/png"; }
  8556. if (samples === void 0) { samples = 1; }
  8557. if (antialiasing === void 0) { antialiasing = false; }
  8558. var width;
  8559. var height;
  8560. //If a precision value is specified
  8561. if (size.precision) {
  8562. width = Math.round(engine.getRenderWidth() * size.precision);
  8563. height = Math.round(width / engine.getAspectRatio(camera));
  8564. size = { width: width, height: height };
  8565. }
  8566. else if (size.width && size.height) {
  8567. width = size.width;
  8568. height = size.height;
  8569. }
  8570. else if (size.width && !size.height) {
  8571. width = size.width;
  8572. height = Math.round(width / engine.getAspectRatio(camera));
  8573. size = { width: width, height: height };
  8574. }
  8575. else if (size.height && !size.width) {
  8576. height = size.height;
  8577. width = Math.round(height * engine.getAspectRatio(camera));
  8578. size = { width: width, height: height };
  8579. }
  8580. else if (!isNaN(size)) {
  8581. height = size;
  8582. width = size;
  8583. }
  8584. else {
  8585. Tools.Error("Invalid 'size' parameter !");
  8586. return;
  8587. }
  8588. var scene = camera.getScene();
  8589. var previousCamera = null;
  8590. if (scene.activeCamera !== camera) {
  8591. previousCamera = scene.activeCamera;
  8592. scene.activeCamera = camera;
  8593. }
  8594. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8595. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8596. texture.renderList = null;
  8597. texture.samples = samples;
  8598. if (antialiasing) {
  8599. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8600. }
  8601. texture.onAfterRenderObservable.add(function () {
  8602. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8603. });
  8604. scene.incrementRenderId();
  8605. scene.resetCachedMaterial();
  8606. texture.render(true);
  8607. texture.dispose();
  8608. if (previousCamera) {
  8609. scene.activeCamera = previousCamera;
  8610. }
  8611. camera.getProjectionMatrix(true); // Force cache refresh;
  8612. };
  8613. // XHR response validator for local file scenario
  8614. Tools.ValidateXHRData = function (xhr, dataType) {
  8615. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8616. if (dataType === void 0) { dataType = 7; }
  8617. try {
  8618. if (dataType & 1) {
  8619. if (xhr.responseText && xhr.responseText.length > 0) {
  8620. return true;
  8621. }
  8622. else if (dataType === 1) {
  8623. return false;
  8624. }
  8625. }
  8626. if (dataType & 2) {
  8627. // Check header width and height since there is no "TGA" magic number
  8628. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8629. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8630. return true;
  8631. }
  8632. else if (dataType === 2) {
  8633. return false;
  8634. }
  8635. }
  8636. if (dataType & 4) {
  8637. // Check for the "DDS" magic number
  8638. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8639. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8640. return true;
  8641. }
  8642. else {
  8643. return false;
  8644. }
  8645. }
  8646. }
  8647. catch (e) {
  8648. // Global protection
  8649. }
  8650. return false;
  8651. };
  8652. /**
  8653. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8654. * Be aware Math.random() could cause collisions, but:
  8655. * "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"
  8656. */
  8657. Tools.RandomId = function () {
  8658. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8659. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8660. return v.toString(16);
  8661. });
  8662. };
  8663. /**
  8664. * Test if the given uri is a base64 string.
  8665. * @param uri The uri to test
  8666. * @return True if the uri is a base64 string or false otherwise.
  8667. */
  8668. Tools.IsBase64 = function (uri) {
  8669. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8670. };
  8671. /**
  8672. * Decode the given base64 uri.
  8673. * @param uri The uri to decode
  8674. * @return The decoded base64 data.
  8675. */
  8676. Tools.DecodeBase64 = function (uri) {
  8677. var decodedString = atob(uri.split(",")[1]);
  8678. var bufferLength = decodedString.length;
  8679. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8680. for (var i = 0; i < bufferLength; i++) {
  8681. bufferView[i] = decodedString.charCodeAt(i);
  8682. }
  8683. return bufferView.buffer;
  8684. };
  8685. Object.defineProperty(Tools, "NoneLogLevel", {
  8686. get: function () {
  8687. return Tools._NoneLogLevel;
  8688. },
  8689. enumerable: true,
  8690. configurable: true
  8691. });
  8692. Object.defineProperty(Tools, "MessageLogLevel", {
  8693. get: function () {
  8694. return Tools._MessageLogLevel;
  8695. },
  8696. enumerable: true,
  8697. configurable: true
  8698. });
  8699. Object.defineProperty(Tools, "WarningLogLevel", {
  8700. get: function () {
  8701. return Tools._WarningLogLevel;
  8702. },
  8703. enumerable: true,
  8704. configurable: true
  8705. });
  8706. Object.defineProperty(Tools, "ErrorLogLevel", {
  8707. get: function () {
  8708. return Tools._ErrorLogLevel;
  8709. },
  8710. enumerable: true,
  8711. configurable: true
  8712. });
  8713. Object.defineProperty(Tools, "AllLogLevel", {
  8714. get: function () {
  8715. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8716. },
  8717. enumerable: true,
  8718. configurable: true
  8719. });
  8720. Tools._AddLogEntry = function (entry) {
  8721. Tools._LogCache = entry + Tools._LogCache;
  8722. if (Tools.OnNewCacheEntry) {
  8723. Tools.OnNewCacheEntry(entry);
  8724. }
  8725. };
  8726. Tools._FormatMessage = function (message) {
  8727. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8728. var date = new Date();
  8729. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8730. };
  8731. Tools._LogDisabled = function (message) {
  8732. // nothing to do
  8733. };
  8734. Tools._LogEnabled = function (message) {
  8735. var formattedMessage = Tools._FormatMessage(message);
  8736. console.log("BJS - " + formattedMessage);
  8737. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8738. Tools._AddLogEntry(entry);
  8739. };
  8740. Tools._WarnDisabled = function (message) {
  8741. // nothing to do
  8742. };
  8743. Tools._WarnEnabled = function (message) {
  8744. var formattedMessage = Tools._FormatMessage(message);
  8745. console.warn("BJS - " + formattedMessage);
  8746. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8747. Tools._AddLogEntry(entry);
  8748. };
  8749. Tools._ErrorDisabled = function (message) {
  8750. // nothing to do
  8751. };
  8752. Tools._ErrorEnabled = function (message) {
  8753. Tools.errorsCount++;
  8754. var formattedMessage = Tools._FormatMessage(message);
  8755. console.error("BJS - " + formattedMessage);
  8756. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8757. Tools._AddLogEntry(entry);
  8758. };
  8759. Object.defineProperty(Tools, "LogCache", {
  8760. get: function () {
  8761. return Tools._LogCache;
  8762. },
  8763. enumerable: true,
  8764. configurable: true
  8765. });
  8766. Tools.ClearLogCache = function () {
  8767. Tools._LogCache = "";
  8768. Tools.errorsCount = 0;
  8769. };
  8770. Object.defineProperty(Tools, "LogLevels", {
  8771. set: function (level) {
  8772. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8773. Tools.Log = Tools._LogEnabled;
  8774. }
  8775. else {
  8776. Tools.Log = Tools._LogDisabled;
  8777. }
  8778. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8779. Tools.Warn = Tools._WarnEnabled;
  8780. }
  8781. else {
  8782. Tools.Warn = Tools._WarnDisabled;
  8783. }
  8784. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8785. Tools.Error = Tools._ErrorEnabled;
  8786. }
  8787. else {
  8788. Tools.Error = Tools._ErrorDisabled;
  8789. }
  8790. },
  8791. enumerable: true,
  8792. configurable: true
  8793. });
  8794. Tools.IsWindowObjectExist = function () {
  8795. return (typeof window) !== "undefined";
  8796. };
  8797. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8798. get: function () {
  8799. return Tools._PerformanceNoneLogLevel;
  8800. },
  8801. enumerable: true,
  8802. configurable: true
  8803. });
  8804. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8805. get: function () {
  8806. return Tools._PerformanceUserMarkLogLevel;
  8807. },
  8808. enumerable: true,
  8809. configurable: true
  8810. });
  8811. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8812. get: function () {
  8813. return Tools._PerformanceConsoleLogLevel;
  8814. },
  8815. enumerable: true,
  8816. configurable: true
  8817. });
  8818. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8819. set: function (level) {
  8820. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8821. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8822. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8823. return;
  8824. }
  8825. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8826. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8827. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8828. return;
  8829. }
  8830. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8831. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8832. },
  8833. enumerable: true,
  8834. configurable: true
  8835. });
  8836. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8837. };
  8838. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8839. };
  8840. Tools._StartUserMark = function (counterName, condition) {
  8841. if (condition === void 0) { condition = true; }
  8842. if (!Tools._performance) {
  8843. if (!Tools.IsWindowObjectExist()) {
  8844. return;
  8845. }
  8846. Tools._performance = window.performance;
  8847. }
  8848. if (!condition || !Tools._performance.mark) {
  8849. return;
  8850. }
  8851. Tools._performance.mark(counterName + "-Begin");
  8852. };
  8853. Tools._EndUserMark = function (counterName, condition) {
  8854. if (condition === void 0) { condition = true; }
  8855. if (!condition || !Tools._performance.mark) {
  8856. return;
  8857. }
  8858. Tools._performance.mark(counterName + "-End");
  8859. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  8860. };
  8861. Tools._StartPerformanceConsole = function (counterName, condition) {
  8862. if (condition === void 0) { condition = true; }
  8863. if (!condition) {
  8864. return;
  8865. }
  8866. Tools._StartUserMark(counterName, condition);
  8867. if (console.time) {
  8868. console.time(counterName);
  8869. }
  8870. };
  8871. Tools._EndPerformanceConsole = function (counterName, condition) {
  8872. if (condition === void 0) { condition = true; }
  8873. if (!condition) {
  8874. return;
  8875. }
  8876. Tools._EndUserMark(counterName, condition);
  8877. if (console.time) {
  8878. console.timeEnd(counterName);
  8879. }
  8880. };
  8881. Object.defineProperty(Tools, "Now", {
  8882. get: function () {
  8883. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  8884. return window.performance.now();
  8885. }
  8886. return new Date().getTime();
  8887. },
  8888. enumerable: true,
  8889. configurable: true
  8890. });
  8891. /**
  8892. * This method will return the name of the class used to create the instance of the given object.
  8893. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  8894. * @param object the object to get the class name from
  8895. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  8896. */
  8897. Tools.GetClassName = function (object, isType) {
  8898. if (isType === void 0) { isType = false; }
  8899. var name = null;
  8900. if (!isType && object.getClassName) {
  8901. name = object.getClassName();
  8902. }
  8903. else {
  8904. if (object instanceof Object) {
  8905. var classObj = isType ? object : Object.getPrototypeOf(object);
  8906. name = classObj.constructor["__bjsclassName__"];
  8907. }
  8908. if (!name) {
  8909. name = typeof object;
  8910. }
  8911. }
  8912. return name;
  8913. };
  8914. Tools.First = function (array, predicate) {
  8915. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  8916. var el = array_1[_i];
  8917. if (predicate(el)) {
  8918. return el;
  8919. }
  8920. }
  8921. return null;
  8922. };
  8923. /**
  8924. * This method will return the name of the full name of the class, including its owning module (if any).
  8925. * 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).
  8926. * @param object the object to get the class name from
  8927. * @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.
  8928. */
  8929. Tools.getFullClassName = function (object, isType) {
  8930. if (isType === void 0) { isType = false; }
  8931. var className = null;
  8932. var moduleName = null;
  8933. if (!isType && object.getClassName) {
  8934. className = object.getClassName();
  8935. }
  8936. else {
  8937. if (object instanceof Object) {
  8938. var classObj = isType ? object : Object.getPrototypeOf(object);
  8939. className = classObj.constructor["__bjsclassName__"];
  8940. moduleName = classObj.constructor["__bjsmoduleName__"];
  8941. }
  8942. if (!className) {
  8943. className = typeof object;
  8944. }
  8945. }
  8946. if (!className) {
  8947. return null;
  8948. }
  8949. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  8950. };
  8951. /**
  8952. * 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.
  8953. * @param array
  8954. */
  8955. Tools.arrayOrStringFeeder = function (array) {
  8956. return function (index) {
  8957. if (index >= array.length) {
  8958. return null;
  8959. }
  8960. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  8961. if (val && val.getHashCode) {
  8962. val = val.getHashCode();
  8963. }
  8964. if (typeof val === "string") {
  8965. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  8966. }
  8967. return val;
  8968. };
  8969. };
  8970. /**
  8971. * Compute the hashCode of a stream of number
  8972. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  8973. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  8974. * @return the hash code computed
  8975. */
  8976. Tools.hashCodeFromStream = function (feeder) {
  8977. // Based from here: http://stackoverflow.com/a/7616484/802124
  8978. var hash = 0;
  8979. var index = 0;
  8980. var chr = feeder(index++);
  8981. while (chr != null) {
  8982. hash = ((hash << 5) - hash) + chr;
  8983. hash |= 0; // Convert to 32bit integer
  8984. chr = feeder(index++);
  8985. }
  8986. return hash;
  8987. };
  8988. /**
  8989. * Returns a promise that resolves after the given amount of time.
  8990. * @param delay Number of milliseconds to delay
  8991. * @returns Promise that resolves after the given amount of time
  8992. */
  8993. Tools.DelayAsync = function (delay) {
  8994. return new Promise(function (resolve) {
  8995. setTimeout(function () {
  8996. resolve();
  8997. }, delay);
  8998. });
  8999. };
  9000. Tools.BaseUrl = "";
  9001. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9002. /**
  9003. * Default behaviour for cors in the application.
  9004. * It can be a string if the expected behavior is identical in the entire app.
  9005. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9006. */
  9007. Tools.CorsBehavior = "anonymous";
  9008. Tools.UseFallbackTexture = true;
  9009. /**
  9010. * Use this object to register external classes like custom textures or material
  9011. * to allow the laoders to instantiate them
  9012. */
  9013. Tools.RegisteredExternalClasses = {};
  9014. // Used in case of a texture loading problem
  9015. 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";
  9016. Tools.PreprocessUrl = function (url) {
  9017. return url;
  9018. };
  9019. // Logs
  9020. Tools._NoneLogLevel = 0;
  9021. Tools._MessageLogLevel = 1;
  9022. Tools._WarningLogLevel = 2;
  9023. Tools._ErrorLogLevel = 4;
  9024. Tools._LogCache = "";
  9025. Tools.errorsCount = 0;
  9026. Tools.Log = Tools._LogEnabled;
  9027. Tools.Warn = Tools._WarnEnabled;
  9028. Tools.Error = Tools._ErrorEnabled;
  9029. // Performances
  9030. Tools._PerformanceNoneLogLevel = 0;
  9031. Tools._PerformanceUserMarkLogLevel = 1;
  9032. Tools._PerformanceConsoleLogLevel = 2;
  9033. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9034. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9035. return Tools;
  9036. }());
  9037. BABYLON.Tools = Tools;
  9038. /**
  9039. * This class is used to track a performance counter which is number based.
  9040. * The user has access to many properties which give statistics of different nature
  9041. *
  9042. * The implementer can track two kinds of Performance Counter: time and count
  9043. * 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.
  9044. * 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.
  9045. */
  9046. var PerfCounter = /** @class */ (function () {
  9047. function PerfCounter() {
  9048. this._startMonitoringTime = 0;
  9049. this._min = 0;
  9050. this._max = 0;
  9051. this._average = 0;
  9052. this._lastSecAverage = 0;
  9053. this._current = 0;
  9054. this._totalValueCount = 0;
  9055. this._totalAccumulated = 0;
  9056. this._lastSecAccumulated = 0;
  9057. this._lastSecTime = 0;
  9058. this._lastSecValueCount = 0;
  9059. }
  9060. Object.defineProperty(PerfCounter.prototype, "min", {
  9061. /**
  9062. * Returns the smallest value ever
  9063. */
  9064. get: function () {
  9065. return this._min;
  9066. },
  9067. enumerable: true,
  9068. configurable: true
  9069. });
  9070. Object.defineProperty(PerfCounter.prototype, "max", {
  9071. /**
  9072. * Returns the biggest value ever
  9073. */
  9074. get: function () {
  9075. return this._max;
  9076. },
  9077. enumerable: true,
  9078. configurable: true
  9079. });
  9080. Object.defineProperty(PerfCounter.prototype, "average", {
  9081. /**
  9082. * Returns the average value since the performance counter is running
  9083. */
  9084. get: function () {
  9085. return this._average;
  9086. },
  9087. enumerable: true,
  9088. configurable: true
  9089. });
  9090. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9091. /**
  9092. * Returns the average value of the last second the counter was monitored
  9093. */
  9094. get: function () {
  9095. return this._lastSecAverage;
  9096. },
  9097. enumerable: true,
  9098. configurable: true
  9099. });
  9100. Object.defineProperty(PerfCounter.prototype, "current", {
  9101. /**
  9102. * Returns the current value
  9103. */
  9104. get: function () {
  9105. return this._current;
  9106. },
  9107. enumerable: true,
  9108. configurable: true
  9109. });
  9110. Object.defineProperty(PerfCounter.prototype, "total", {
  9111. get: function () {
  9112. return this._totalAccumulated;
  9113. },
  9114. enumerable: true,
  9115. configurable: true
  9116. });
  9117. Object.defineProperty(PerfCounter.prototype, "count", {
  9118. get: function () {
  9119. return this._totalValueCount;
  9120. },
  9121. enumerable: true,
  9122. configurable: true
  9123. });
  9124. /**
  9125. * Call this method to start monitoring a new frame.
  9126. * 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.
  9127. */
  9128. PerfCounter.prototype.fetchNewFrame = function () {
  9129. this._totalValueCount++;
  9130. this._current = 0;
  9131. this._lastSecValueCount++;
  9132. };
  9133. /**
  9134. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9135. * @param newCount the count value to add to the monitored count
  9136. * @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.
  9137. */
  9138. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9139. if (!PerfCounter.Enabled) {
  9140. return;
  9141. }
  9142. this._current += newCount;
  9143. if (fetchResult) {
  9144. this._fetchResult();
  9145. }
  9146. };
  9147. /**
  9148. * Start monitoring this performance counter
  9149. */
  9150. PerfCounter.prototype.beginMonitoring = function () {
  9151. if (!PerfCounter.Enabled) {
  9152. return;
  9153. }
  9154. this._startMonitoringTime = Tools.Now;
  9155. };
  9156. /**
  9157. * Compute the time lapsed since the previous beginMonitoring() call.
  9158. * @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
  9159. */
  9160. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9161. if (newFrame === void 0) { newFrame = true; }
  9162. if (!PerfCounter.Enabled) {
  9163. return;
  9164. }
  9165. if (newFrame) {
  9166. this.fetchNewFrame();
  9167. }
  9168. var currentTime = Tools.Now;
  9169. this._current = currentTime - this._startMonitoringTime;
  9170. if (newFrame) {
  9171. this._fetchResult();
  9172. }
  9173. };
  9174. PerfCounter.prototype._fetchResult = function () {
  9175. this._totalAccumulated += this._current;
  9176. this._lastSecAccumulated += this._current;
  9177. // Min/Max update
  9178. this._min = Math.min(this._min, this._current);
  9179. this._max = Math.max(this._max, this._current);
  9180. this._average = this._totalAccumulated / this._totalValueCount;
  9181. // Reset last sec?
  9182. var now = Tools.Now;
  9183. if ((now - this._lastSecTime) > 1000) {
  9184. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9185. this._lastSecTime = now;
  9186. this._lastSecAccumulated = 0;
  9187. this._lastSecValueCount = 0;
  9188. }
  9189. };
  9190. PerfCounter.Enabled = true;
  9191. return PerfCounter;
  9192. }());
  9193. BABYLON.PerfCounter = PerfCounter;
  9194. /**
  9195. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9196. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9197. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9198. * @param name The name of the class, case should be preserved
  9199. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9200. */
  9201. function className(name, module) {
  9202. return function (target) {
  9203. target["__bjsclassName__"] = name;
  9204. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9205. };
  9206. }
  9207. BABYLON.className = className;
  9208. /**
  9209. * An implementation of a loop for asynchronous functions.
  9210. */
  9211. var AsyncLoop = /** @class */ (function () {
  9212. /**
  9213. * Constroctor.
  9214. * @param iterations the number of iterations.
  9215. * @param _fn the function to run each iteration
  9216. * @param _successCallback the callback that will be called upon succesful execution
  9217. * @param offset starting offset.
  9218. */
  9219. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9220. if (offset === void 0) { offset = 0; }
  9221. this.iterations = iterations;
  9222. this._fn = _fn;
  9223. this._successCallback = _successCallback;
  9224. this.index = offset - 1;
  9225. this._done = false;
  9226. }
  9227. /**
  9228. * Execute the next iteration. Must be called after the last iteration was finished.
  9229. */
  9230. AsyncLoop.prototype.executeNext = function () {
  9231. if (!this._done) {
  9232. if (this.index + 1 < this.iterations) {
  9233. ++this.index;
  9234. this._fn(this);
  9235. }
  9236. else {
  9237. this.breakLoop();
  9238. }
  9239. }
  9240. };
  9241. /**
  9242. * Break the loop and run the success callback.
  9243. */
  9244. AsyncLoop.prototype.breakLoop = function () {
  9245. this._done = true;
  9246. this._successCallback();
  9247. };
  9248. /**
  9249. * Helper function
  9250. */
  9251. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9252. if (offset === void 0) { offset = 0; }
  9253. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9254. loop.executeNext();
  9255. return loop;
  9256. };
  9257. /**
  9258. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9259. * @param iterations total number of iterations
  9260. * @param syncedIterations number of synchronous iterations in each async iteration.
  9261. * @param fn the function to call each iteration.
  9262. * @param callback a success call back that will be called when iterating stops.
  9263. * @param breakFunction a break condition (optional)
  9264. * @param timeout timeout settings for the setTimeout function. default - 0.
  9265. * @constructor
  9266. */
  9267. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9268. if (timeout === void 0) { timeout = 0; }
  9269. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9270. if (breakFunction && breakFunction())
  9271. loop.breakLoop();
  9272. else {
  9273. setTimeout(function () {
  9274. for (var i = 0; i < syncedIterations; ++i) {
  9275. var iteration = (loop.index * syncedIterations) + i;
  9276. if (iteration >= iterations)
  9277. break;
  9278. fn(iteration);
  9279. if (breakFunction && breakFunction()) {
  9280. loop.breakLoop();
  9281. break;
  9282. }
  9283. }
  9284. loop.executeNext();
  9285. }, timeout);
  9286. }
  9287. }, callback);
  9288. };
  9289. return AsyncLoop;
  9290. }());
  9291. BABYLON.AsyncLoop = AsyncLoop;
  9292. })(BABYLON || (BABYLON = {}));
  9293. //# sourceMappingURL=babylon.tools.js.map
  9294. var BABYLON;
  9295. (function (BABYLON) {
  9296. var PromiseStates;
  9297. (function (PromiseStates) {
  9298. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9299. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9300. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9301. })(PromiseStates || (PromiseStates = {}));
  9302. var FulFillmentAgregator = /** @class */ (function () {
  9303. function FulFillmentAgregator() {
  9304. this.count = 0;
  9305. this.target = 0;
  9306. this.results = [];
  9307. }
  9308. return FulFillmentAgregator;
  9309. }());
  9310. var InternalPromise = /** @class */ (function () {
  9311. function InternalPromise(resolver) {
  9312. var _this = this;
  9313. this._state = PromiseStates.Pending;
  9314. this._children = new Array();
  9315. this._rejectWasConsumed = false;
  9316. if (!resolver) {
  9317. return;
  9318. }
  9319. try {
  9320. resolver(function (value) {
  9321. _this._resolve(value);
  9322. }, function (reason) {
  9323. _this._reject(reason);
  9324. });
  9325. }
  9326. catch (e) {
  9327. this._reject(e);
  9328. }
  9329. }
  9330. InternalPromise.prototype.catch = function (onRejected) {
  9331. return this.then(undefined, onRejected);
  9332. };
  9333. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9334. var _this = this;
  9335. var newPromise = new InternalPromise();
  9336. newPromise._onFulfilled = onFulfilled;
  9337. newPromise._onRejected = onRejected;
  9338. // Composition
  9339. this._children.push(newPromise);
  9340. if (this._state !== PromiseStates.Pending) {
  9341. BABYLON.Tools.SetImmediate(function () {
  9342. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9343. var returnedValue = newPromise._resolve(_this._result);
  9344. if (returnedValue !== undefined && returnedValue !== null) {
  9345. if (returnedValue._state !== undefined) {
  9346. var returnedPromise = returnedValue;
  9347. newPromise._children.push(returnedPromise);
  9348. newPromise = returnedPromise;
  9349. }
  9350. else {
  9351. newPromise._result = returnedValue;
  9352. }
  9353. }
  9354. }
  9355. else {
  9356. newPromise._reject(_this._reason);
  9357. }
  9358. });
  9359. }
  9360. return newPromise;
  9361. };
  9362. InternalPromise.prototype._moveChildren = function (children) {
  9363. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9364. if (this._state === PromiseStates.Fulfilled) {
  9365. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9366. var child = _b[_i];
  9367. child._resolve(this._result);
  9368. }
  9369. }
  9370. else if (this._state === PromiseStates.Rejected) {
  9371. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9372. var child = _d[_c];
  9373. child._reject(this._reason);
  9374. }
  9375. }
  9376. var _a;
  9377. };
  9378. InternalPromise.prototype._resolve = function (value) {
  9379. try {
  9380. this._state = PromiseStates.Fulfilled;
  9381. this._result = value;
  9382. var returnedValue = null;
  9383. if (this._onFulfilled) {
  9384. returnedValue = this._onFulfilled(value);
  9385. }
  9386. if (returnedValue !== undefined && returnedValue !== null) {
  9387. if (returnedValue._state !== undefined) {
  9388. // Transmit children
  9389. var returnedPromise = returnedValue;
  9390. returnedPromise._moveChildren(this._children);
  9391. }
  9392. else {
  9393. value = returnedValue;
  9394. }
  9395. }
  9396. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9397. var child = _a[_i];
  9398. child._resolve(value);
  9399. }
  9400. this._children.length = 0;
  9401. delete this._onFulfilled;
  9402. delete this._onRejected;
  9403. return returnedValue;
  9404. }
  9405. catch (e) {
  9406. this._reject(e, true);
  9407. }
  9408. return null;
  9409. };
  9410. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9411. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9412. this._state = PromiseStates.Rejected;
  9413. this._reason = reason;
  9414. if (this._onRejected && !onLocalThrow) {
  9415. try {
  9416. this._onRejected(reason);
  9417. this._rejectWasConsumed = true;
  9418. }
  9419. catch (e) {
  9420. reason = e;
  9421. }
  9422. }
  9423. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9424. var child = _a[_i];
  9425. if (this._rejectWasConsumed) {
  9426. child._resolve(null);
  9427. }
  9428. else {
  9429. child._reject(reason);
  9430. }
  9431. }
  9432. this._children.length = 0;
  9433. delete this._onFulfilled;
  9434. delete this._onRejected;
  9435. };
  9436. InternalPromise.resolve = function (value) {
  9437. var newPromise = new InternalPromise();
  9438. newPromise._resolve(value);
  9439. return newPromise;
  9440. };
  9441. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9442. promise.then(function (value) {
  9443. agregator.results[index] = value;
  9444. agregator.count++;
  9445. if (agregator.count === agregator.target) {
  9446. agregator.rootPromise._resolve(agregator.results);
  9447. }
  9448. return null;
  9449. }, function (reason) {
  9450. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9451. agregator.rootPromise._reject(reason);
  9452. }
  9453. });
  9454. };
  9455. InternalPromise.all = function (promises) {
  9456. var newPromise = new InternalPromise();
  9457. var agregator = new FulFillmentAgregator();
  9458. agregator.target = promises.length;
  9459. agregator.rootPromise = newPromise;
  9460. if (promises.length) {
  9461. for (var index = 0; index < promises.length; index++) {
  9462. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9463. }
  9464. }
  9465. else {
  9466. newPromise._resolve([]);
  9467. }
  9468. return newPromise;
  9469. };
  9470. return InternalPromise;
  9471. }());
  9472. /**
  9473. * Helper class that provides a small promise polyfill
  9474. */
  9475. var PromisePolyfill = /** @class */ (function () {
  9476. function PromisePolyfill() {
  9477. }
  9478. /**
  9479. * Static function used to check if the polyfill is required
  9480. * If this is the case then the function will inject the polyfill to window.Promise
  9481. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9482. */
  9483. PromisePolyfill.Apply = function (force) {
  9484. if (force === void 0) { force = false; }
  9485. if (force || typeof Promise === 'undefined') {
  9486. var root = window;
  9487. root.Promise = InternalPromise;
  9488. }
  9489. };
  9490. return PromisePolyfill;
  9491. }());
  9492. BABYLON.PromisePolyfill = PromisePolyfill;
  9493. })(BABYLON || (BABYLON = {}));
  9494. //# sourceMappingURL=babylon.promise.js.map
  9495. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9496. var BABYLON;
  9497. (function (BABYLON) {
  9498. /**
  9499. * Helper class to push actions to a pool of workers.
  9500. */
  9501. var WorkerPool = /** @class */ (function () {
  9502. /**
  9503. * Constructor
  9504. * @param workers Array of workers to use for actions
  9505. */
  9506. function WorkerPool(workers) {
  9507. this._pendingActions = new Array();
  9508. this._workerInfos = workers.map(function (worker) { return ({
  9509. worker: worker,
  9510. active: false
  9511. }); });
  9512. }
  9513. /**
  9514. * Terminates all workers and clears any pending actions.
  9515. */
  9516. WorkerPool.prototype.dispose = function () {
  9517. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9518. var workerInfo = _a[_i];
  9519. workerInfo.worker.terminate();
  9520. }
  9521. delete this._workerInfos;
  9522. delete this._pendingActions;
  9523. };
  9524. /**
  9525. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9526. * pended until a worker has completed its action.
  9527. * @param action The action to perform. Call onComplete when the action is complete.
  9528. */
  9529. WorkerPool.prototype.push = function (action) {
  9530. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9531. var workerInfo = _a[_i];
  9532. if (!workerInfo.active) {
  9533. this._execute(workerInfo, action);
  9534. return;
  9535. }
  9536. }
  9537. this._pendingActions.push(action);
  9538. };
  9539. WorkerPool.prototype._execute = function (workerInfo, action) {
  9540. var _this = this;
  9541. workerInfo.active = true;
  9542. action(workerInfo.worker, function () {
  9543. workerInfo.active = false;
  9544. var nextAction = _this._pendingActions.shift();
  9545. if (nextAction) {
  9546. _this._execute(workerInfo, nextAction);
  9547. }
  9548. });
  9549. };
  9550. return WorkerPool;
  9551. }());
  9552. BABYLON.WorkerPool = WorkerPool;
  9553. })(BABYLON || (BABYLON = {}));
  9554. //# sourceMappingURL=babylon.workerPool.js.map
  9555. var BABYLON;
  9556. (function (BABYLON) {
  9557. var _AlphaState = /** @class */ (function () {
  9558. /**
  9559. * Initializes the state.
  9560. */
  9561. function _AlphaState() {
  9562. this._isAlphaBlendDirty = false;
  9563. this._isBlendFunctionParametersDirty = false;
  9564. this._isBlendEquationParametersDirty = false;
  9565. this._isBlendConstantsDirty = false;
  9566. this._alphaBlend = false;
  9567. this._blendFunctionParameters = new Array(4);
  9568. this._blendEquationParameters = new Array(2);
  9569. this._blendConstants = new Array(4);
  9570. this.reset();
  9571. }
  9572. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9573. get: function () {
  9574. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9575. },
  9576. enumerable: true,
  9577. configurable: true
  9578. });
  9579. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9580. get: function () {
  9581. return this._alphaBlend;
  9582. },
  9583. set: function (value) {
  9584. if (this._alphaBlend === value) {
  9585. return;
  9586. }
  9587. this._alphaBlend = value;
  9588. this._isAlphaBlendDirty = true;
  9589. },
  9590. enumerable: true,
  9591. configurable: true
  9592. });
  9593. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9594. if (this._blendConstants[0] === r &&
  9595. this._blendConstants[1] === g &&
  9596. this._blendConstants[2] === b &&
  9597. this._blendConstants[3] === a) {
  9598. return;
  9599. }
  9600. this._blendConstants[0] = r;
  9601. this._blendConstants[1] = g;
  9602. this._blendConstants[2] = b;
  9603. this._blendConstants[3] = a;
  9604. this._isBlendConstantsDirty = true;
  9605. };
  9606. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9607. if (this._blendFunctionParameters[0] === value0 &&
  9608. this._blendFunctionParameters[1] === value1 &&
  9609. this._blendFunctionParameters[2] === value2 &&
  9610. this._blendFunctionParameters[3] === value3) {
  9611. return;
  9612. }
  9613. this._blendFunctionParameters[0] = value0;
  9614. this._blendFunctionParameters[1] = value1;
  9615. this._blendFunctionParameters[2] = value2;
  9616. this._blendFunctionParameters[3] = value3;
  9617. this._isBlendFunctionParametersDirty = true;
  9618. };
  9619. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9620. if (this._blendEquationParameters[0] === rgb &&
  9621. this._blendEquationParameters[1] === alpha) {
  9622. return;
  9623. }
  9624. this._blendEquationParameters[0] = rgb;
  9625. this._blendEquationParameters[1] = alpha;
  9626. this._isBlendEquationParametersDirty = true;
  9627. };
  9628. _AlphaState.prototype.reset = function () {
  9629. this._alphaBlend = false;
  9630. this._blendFunctionParameters[0] = null;
  9631. this._blendFunctionParameters[1] = null;
  9632. this._blendFunctionParameters[2] = null;
  9633. this._blendFunctionParameters[3] = null;
  9634. this._blendEquationParameters[0] = null;
  9635. this._blendEquationParameters[1] = null;
  9636. this._blendConstants[0] = null;
  9637. this._blendConstants[1] = null;
  9638. this._blendConstants[2] = null;
  9639. this._blendConstants[3] = null;
  9640. this._isAlphaBlendDirty = true;
  9641. this._isBlendFunctionParametersDirty = false;
  9642. this._isBlendEquationParametersDirty = false;
  9643. this._isBlendConstantsDirty = false;
  9644. };
  9645. _AlphaState.prototype.apply = function (gl) {
  9646. if (!this.isDirty) {
  9647. return;
  9648. }
  9649. // Alpha blend
  9650. if (this._isAlphaBlendDirty) {
  9651. if (this._alphaBlend) {
  9652. gl.enable(gl.BLEND);
  9653. }
  9654. else {
  9655. gl.disable(gl.BLEND);
  9656. }
  9657. this._isAlphaBlendDirty = false;
  9658. }
  9659. // Alpha function
  9660. if (this._isBlendFunctionParametersDirty) {
  9661. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9662. this._isBlendFunctionParametersDirty = false;
  9663. }
  9664. // Alpha equation
  9665. if (this._isBlendEquationParametersDirty) {
  9666. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9667. this._isBlendEquationParametersDirty = false;
  9668. }
  9669. // Constants
  9670. if (this._isBlendConstantsDirty) {
  9671. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9672. this._isBlendConstantsDirty = false;
  9673. }
  9674. };
  9675. return _AlphaState;
  9676. }());
  9677. BABYLON._AlphaState = _AlphaState;
  9678. })(BABYLON || (BABYLON = {}));
  9679. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9680. var BABYLON;
  9681. (function (BABYLON) {
  9682. var _DepthCullingState = /** @class */ (function () {
  9683. /**
  9684. * Initializes the state.
  9685. */
  9686. function _DepthCullingState() {
  9687. this._isDepthTestDirty = false;
  9688. this._isDepthMaskDirty = false;
  9689. this._isDepthFuncDirty = false;
  9690. this._isCullFaceDirty = false;
  9691. this._isCullDirty = false;
  9692. this._isZOffsetDirty = false;
  9693. this._isFrontFaceDirty = false;
  9694. this.reset();
  9695. }
  9696. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9697. get: function () {
  9698. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9699. },
  9700. enumerable: true,
  9701. configurable: true
  9702. });
  9703. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9704. get: function () {
  9705. return this._zOffset;
  9706. },
  9707. set: function (value) {
  9708. if (this._zOffset === value) {
  9709. return;
  9710. }
  9711. this._zOffset = value;
  9712. this._isZOffsetDirty = true;
  9713. },
  9714. enumerable: true,
  9715. configurable: true
  9716. });
  9717. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9718. get: function () {
  9719. return this._cullFace;
  9720. },
  9721. set: function (value) {
  9722. if (this._cullFace === value) {
  9723. return;
  9724. }
  9725. this._cullFace = value;
  9726. this._isCullFaceDirty = true;
  9727. },
  9728. enumerable: true,
  9729. configurable: true
  9730. });
  9731. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9732. get: function () {
  9733. return this._cull;
  9734. },
  9735. set: function (value) {
  9736. if (this._cull === value) {
  9737. return;
  9738. }
  9739. this._cull = value;
  9740. this._isCullDirty = true;
  9741. },
  9742. enumerable: true,
  9743. configurable: true
  9744. });
  9745. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9746. get: function () {
  9747. return this._depthFunc;
  9748. },
  9749. set: function (value) {
  9750. if (this._depthFunc === value) {
  9751. return;
  9752. }
  9753. this._depthFunc = value;
  9754. this._isDepthFuncDirty = true;
  9755. },
  9756. enumerable: true,
  9757. configurable: true
  9758. });
  9759. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9760. get: function () {
  9761. return this._depthMask;
  9762. },
  9763. set: function (value) {
  9764. if (this._depthMask === value) {
  9765. return;
  9766. }
  9767. this._depthMask = value;
  9768. this._isDepthMaskDirty = true;
  9769. },
  9770. enumerable: true,
  9771. configurable: true
  9772. });
  9773. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9774. get: function () {
  9775. return this._depthTest;
  9776. },
  9777. set: function (value) {
  9778. if (this._depthTest === value) {
  9779. return;
  9780. }
  9781. this._depthTest = value;
  9782. this._isDepthTestDirty = true;
  9783. },
  9784. enumerable: true,
  9785. configurable: true
  9786. });
  9787. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9788. get: function () {
  9789. return this._frontFace;
  9790. },
  9791. set: function (value) {
  9792. if (this._frontFace === value) {
  9793. return;
  9794. }
  9795. this._frontFace = value;
  9796. this._isFrontFaceDirty = true;
  9797. },
  9798. enumerable: true,
  9799. configurable: true
  9800. });
  9801. _DepthCullingState.prototype.reset = function () {
  9802. this._depthMask = true;
  9803. this._depthTest = true;
  9804. this._depthFunc = null;
  9805. this._cullFace = null;
  9806. this._cull = null;
  9807. this._zOffset = 0;
  9808. this._frontFace = null;
  9809. this._isDepthTestDirty = true;
  9810. this._isDepthMaskDirty = true;
  9811. this._isDepthFuncDirty = false;
  9812. this._isCullFaceDirty = false;
  9813. this._isCullDirty = false;
  9814. this._isZOffsetDirty = false;
  9815. this._isFrontFaceDirty = false;
  9816. };
  9817. _DepthCullingState.prototype.apply = function (gl) {
  9818. if (!this.isDirty) {
  9819. return;
  9820. }
  9821. // Cull
  9822. if (this._isCullDirty) {
  9823. if (this.cull) {
  9824. gl.enable(gl.CULL_FACE);
  9825. }
  9826. else {
  9827. gl.disable(gl.CULL_FACE);
  9828. }
  9829. this._isCullDirty = false;
  9830. }
  9831. // Cull face
  9832. if (this._isCullFaceDirty) {
  9833. gl.cullFace(this.cullFace);
  9834. this._isCullFaceDirty = false;
  9835. }
  9836. // Depth mask
  9837. if (this._isDepthMaskDirty) {
  9838. gl.depthMask(this.depthMask);
  9839. this._isDepthMaskDirty = false;
  9840. }
  9841. // Depth test
  9842. if (this._isDepthTestDirty) {
  9843. if (this.depthTest) {
  9844. gl.enable(gl.DEPTH_TEST);
  9845. }
  9846. else {
  9847. gl.disable(gl.DEPTH_TEST);
  9848. }
  9849. this._isDepthTestDirty = false;
  9850. }
  9851. // Depth func
  9852. if (this._isDepthFuncDirty) {
  9853. gl.depthFunc(this.depthFunc);
  9854. this._isDepthFuncDirty = false;
  9855. }
  9856. // zOffset
  9857. if (this._isZOffsetDirty) {
  9858. if (this.zOffset) {
  9859. gl.enable(gl.POLYGON_OFFSET_FILL);
  9860. gl.polygonOffset(this.zOffset, 0);
  9861. }
  9862. else {
  9863. gl.disable(gl.POLYGON_OFFSET_FILL);
  9864. }
  9865. this._isZOffsetDirty = false;
  9866. }
  9867. // Front face
  9868. if (this._isFrontFaceDirty) {
  9869. gl.frontFace(this.frontFace);
  9870. this._isFrontFaceDirty = false;
  9871. }
  9872. };
  9873. return _DepthCullingState;
  9874. }());
  9875. BABYLON._DepthCullingState = _DepthCullingState;
  9876. })(BABYLON || (BABYLON = {}));
  9877. //# sourceMappingURL=babylon.depthCullingState.js.map
  9878. var BABYLON;
  9879. (function (BABYLON) {
  9880. var _StencilState = /** @class */ (function () {
  9881. function _StencilState() {
  9882. this._isStencilTestDirty = false;
  9883. this._isStencilMaskDirty = false;
  9884. this._isStencilFuncDirty = false;
  9885. this._isStencilOpDirty = false;
  9886. this.reset();
  9887. }
  9888. Object.defineProperty(_StencilState.prototype, "isDirty", {
  9889. get: function () {
  9890. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  9891. },
  9892. enumerable: true,
  9893. configurable: true
  9894. });
  9895. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  9896. get: function () {
  9897. return this._stencilFunc;
  9898. },
  9899. set: function (value) {
  9900. if (this._stencilFunc === value) {
  9901. return;
  9902. }
  9903. this._stencilFunc = value;
  9904. this._isStencilFuncDirty = true;
  9905. },
  9906. enumerable: true,
  9907. configurable: true
  9908. });
  9909. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  9910. get: function () {
  9911. return this._stencilFuncRef;
  9912. },
  9913. set: function (value) {
  9914. if (this._stencilFuncRef === value) {
  9915. return;
  9916. }
  9917. this._stencilFuncRef = value;
  9918. this._isStencilFuncDirty = true;
  9919. },
  9920. enumerable: true,
  9921. configurable: true
  9922. });
  9923. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  9924. get: function () {
  9925. return this._stencilFuncMask;
  9926. },
  9927. set: function (value) {
  9928. if (this._stencilFuncMask === value) {
  9929. return;
  9930. }
  9931. this._stencilFuncMask = value;
  9932. this._isStencilFuncDirty = true;
  9933. },
  9934. enumerable: true,
  9935. configurable: true
  9936. });
  9937. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  9938. get: function () {
  9939. return this._stencilOpStencilFail;
  9940. },
  9941. set: function (value) {
  9942. if (this._stencilOpStencilFail === value) {
  9943. return;
  9944. }
  9945. this._stencilOpStencilFail = value;
  9946. this._isStencilOpDirty = true;
  9947. },
  9948. enumerable: true,
  9949. configurable: true
  9950. });
  9951. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  9952. get: function () {
  9953. return this._stencilOpDepthFail;
  9954. },
  9955. set: function (value) {
  9956. if (this._stencilOpDepthFail === value) {
  9957. return;
  9958. }
  9959. this._stencilOpDepthFail = value;
  9960. this._isStencilOpDirty = true;
  9961. },
  9962. enumerable: true,
  9963. configurable: true
  9964. });
  9965. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  9966. get: function () {
  9967. return this._stencilOpStencilDepthPass;
  9968. },
  9969. set: function (value) {
  9970. if (this._stencilOpStencilDepthPass === value) {
  9971. return;
  9972. }
  9973. this._stencilOpStencilDepthPass = value;
  9974. this._isStencilOpDirty = true;
  9975. },
  9976. enumerable: true,
  9977. configurable: true
  9978. });
  9979. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  9980. get: function () {
  9981. return this._stencilMask;
  9982. },
  9983. set: function (value) {
  9984. if (this._stencilMask === value) {
  9985. return;
  9986. }
  9987. this._stencilMask = value;
  9988. this._isStencilMaskDirty = true;
  9989. },
  9990. enumerable: true,
  9991. configurable: true
  9992. });
  9993. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  9994. get: function () {
  9995. return this._stencilTest;
  9996. },
  9997. set: function (value) {
  9998. if (this._stencilTest === value) {
  9999. return;
  10000. }
  10001. this._stencilTest = value;
  10002. this._isStencilTestDirty = true;
  10003. },
  10004. enumerable: true,
  10005. configurable: true
  10006. });
  10007. _StencilState.prototype.reset = function () {
  10008. this._stencilTest = false;
  10009. this._stencilMask = 0xFF;
  10010. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10011. this._stencilFuncRef = 1;
  10012. this._stencilFuncMask = 0xFF;
  10013. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10014. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10015. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10016. this._isStencilTestDirty = true;
  10017. this._isStencilMaskDirty = true;
  10018. this._isStencilFuncDirty = true;
  10019. this._isStencilOpDirty = true;
  10020. };
  10021. _StencilState.prototype.apply = function (gl) {
  10022. if (!this.isDirty) {
  10023. return;
  10024. }
  10025. // Stencil test
  10026. if (this._isStencilTestDirty) {
  10027. if (this.stencilTest) {
  10028. gl.enable(gl.STENCIL_TEST);
  10029. }
  10030. else {
  10031. gl.disable(gl.STENCIL_TEST);
  10032. }
  10033. this._isStencilTestDirty = false;
  10034. }
  10035. // Stencil mask
  10036. if (this._isStencilMaskDirty) {
  10037. gl.stencilMask(this.stencilMask);
  10038. this._isStencilMaskDirty = false;
  10039. }
  10040. // Stencil func
  10041. if (this._isStencilFuncDirty) {
  10042. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10043. this._isStencilFuncDirty = false;
  10044. }
  10045. // Stencil op
  10046. if (this._isStencilOpDirty) {
  10047. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10048. this._isStencilOpDirty = false;
  10049. }
  10050. };
  10051. return _StencilState;
  10052. }());
  10053. BABYLON._StencilState = _StencilState;
  10054. })(BABYLON || (BABYLON = {}));
  10055. //# sourceMappingURL=babylon.stencilState.js.map
  10056. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10057. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10058. s = arguments[i];
  10059. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10060. t[p] = s[p];
  10061. }
  10062. return t;
  10063. };
  10064. var BABYLON;
  10065. (function (BABYLON) {
  10066. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10067. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10068. };
  10069. var compileRawShader = function (gl, source, type) {
  10070. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10071. gl.shaderSource(shader, source);
  10072. gl.compileShader(shader);
  10073. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10074. var log = gl.getShaderInfoLog(shader);
  10075. if (log) {
  10076. throw new Error(log);
  10077. }
  10078. }
  10079. if (!shader) {
  10080. throw new Error("Something went wrong while compile the shader.");
  10081. }
  10082. return shader;
  10083. };
  10084. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10085. var magFilter = gl.NEAREST;
  10086. var minFilter = gl.NEAREST;
  10087. switch (samplingMode) {
  10088. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10089. magFilter = gl.LINEAR;
  10090. if (generateMipMaps) {
  10091. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10092. }
  10093. else {
  10094. minFilter = gl.LINEAR;
  10095. }
  10096. break;
  10097. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10098. magFilter = gl.LINEAR;
  10099. if (generateMipMaps) {
  10100. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10101. }
  10102. else {
  10103. minFilter = gl.LINEAR;
  10104. }
  10105. break;
  10106. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10107. magFilter = gl.NEAREST;
  10108. if (generateMipMaps) {
  10109. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10110. }
  10111. else {
  10112. minFilter = gl.NEAREST;
  10113. }
  10114. break;
  10115. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10116. magFilter = gl.NEAREST;
  10117. if (generateMipMaps) {
  10118. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10119. }
  10120. else {
  10121. minFilter = gl.NEAREST;
  10122. }
  10123. break;
  10124. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10125. magFilter = gl.NEAREST;
  10126. if (generateMipMaps) {
  10127. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10128. }
  10129. else {
  10130. minFilter = gl.LINEAR;
  10131. }
  10132. break;
  10133. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10134. magFilter = gl.NEAREST;
  10135. if (generateMipMaps) {
  10136. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10137. }
  10138. else {
  10139. minFilter = gl.LINEAR;
  10140. }
  10141. break;
  10142. case BABYLON.Texture.NEAREST_LINEAR:
  10143. magFilter = gl.NEAREST;
  10144. minFilter = gl.LINEAR;
  10145. break;
  10146. case BABYLON.Texture.NEAREST_NEAREST:
  10147. magFilter = gl.NEAREST;
  10148. minFilter = gl.NEAREST;
  10149. break;
  10150. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10151. magFilter = gl.LINEAR;
  10152. if (generateMipMaps) {
  10153. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10154. }
  10155. else {
  10156. minFilter = gl.NEAREST;
  10157. }
  10158. break;
  10159. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10160. magFilter = gl.LINEAR;
  10161. if (generateMipMaps) {
  10162. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10163. }
  10164. else {
  10165. minFilter = gl.NEAREST;
  10166. }
  10167. break;
  10168. case BABYLON.Texture.LINEAR_LINEAR:
  10169. magFilter = gl.LINEAR;
  10170. minFilter = gl.LINEAR;
  10171. break;
  10172. case BABYLON.Texture.LINEAR_NEAREST:
  10173. magFilter = gl.LINEAR;
  10174. minFilter = gl.NEAREST;
  10175. break;
  10176. }
  10177. return {
  10178. min: minFilter,
  10179. mag: magFilter
  10180. };
  10181. };
  10182. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10183. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10184. var img;
  10185. var onload = function () {
  10186. loadedImages[index] = img;
  10187. loadedImages._internalCount++;
  10188. if (scene) {
  10189. scene._removePendingData(img);
  10190. }
  10191. if (loadedImages._internalCount === 6) {
  10192. onfinish(loadedImages);
  10193. }
  10194. };
  10195. var onerror = function (message, exception) {
  10196. if (scene) {
  10197. scene._removePendingData(img);
  10198. }
  10199. if (onErrorCallBack) {
  10200. onErrorCallBack(message, exception);
  10201. }
  10202. };
  10203. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10204. if (scene) {
  10205. scene._addPendingData(img);
  10206. }
  10207. };
  10208. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10209. if (onError === void 0) { onError = null; }
  10210. var loadedImages = [];
  10211. loadedImages._internalCount = 0;
  10212. for (var index = 0; index < 6; index++) {
  10213. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10214. }
  10215. };
  10216. var BufferPointer = /** @class */ (function () {
  10217. function BufferPointer() {
  10218. }
  10219. return BufferPointer;
  10220. }());
  10221. var InstancingAttributeInfo = /** @class */ (function () {
  10222. function InstancingAttributeInfo() {
  10223. }
  10224. return InstancingAttributeInfo;
  10225. }());
  10226. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10227. /**
  10228. * Define options used to create a render target texture
  10229. */
  10230. var RenderTargetCreationOptions = /** @class */ (function () {
  10231. function RenderTargetCreationOptions() {
  10232. }
  10233. return RenderTargetCreationOptions;
  10234. }());
  10235. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10236. /**
  10237. * Define options used to create a depth texture
  10238. */
  10239. var DepthTextureCreationOptions = /** @class */ (function () {
  10240. function DepthTextureCreationOptions() {
  10241. }
  10242. return DepthTextureCreationOptions;
  10243. }());
  10244. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10245. /**
  10246. * Regroup several parameters relative to the browser in use
  10247. */
  10248. var EngineCapabilities = /** @class */ (function () {
  10249. function EngineCapabilities() {
  10250. }
  10251. return EngineCapabilities;
  10252. }());
  10253. BABYLON.EngineCapabilities = EngineCapabilities;
  10254. /**
  10255. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10256. */
  10257. var Engine = /** @class */ (function () {
  10258. /**
  10259. * @constructor
  10260. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10261. * @param antialias defines enable antialiasing (default: false)
  10262. * @param options defines further options to be sent to the getContext() function
  10263. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10264. */
  10265. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10266. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10267. var _this = this;
  10268. // Public members
  10269. this.forcePOTTextures = false;
  10270. this.isFullscreen = false;
  10271. this.isPointerLock = false;
  10272. this.cullBackFaces = true;
  10273. this.renderEvenInBackground = true;
  10274. this.preventCacheWipeBetweenFrames = false;
  10275. // To enable/disable IDB support and avoid XHR on .manifest
  10276. this.enableOfflineSupport = false;
  10277. this.scenes = new Array();
  10278. this.postProcesses = new Array();
  10279. // Observables
  10280. /**
  10281. * Observable event triggered each time the rendering canvas is resized
  10282. */
  10283. this.onResizeObservable = new BABYLON.Observable();
  10284. /**
  10285. * Observable event triggered each time the canvas loses focus
  10286. */
  10287. this.onCanvasBlurObservable = new BABYLON.Observable();
  10288. /**
  10289. * Observable event triggered each time the canvas gains focus
  10290. */
  10291. this.onCanvasFocusObservable = new BABYLON.Observable();
  10292. /**
  10293. * Observable event triggered each time the canvas receives pointerout event
  10294. */
  10295. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10296. /**
  10297. * Observable event triggered before each texture is initialized
  10298. */
  10299. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10300. //WebVR
  10301. this._vrDisplay = undefined;
  10302. this._vrSupported = false;
  10303. this._vrExclusivePointerMode = false;
  10304. // Uniform buffers list
  10305. this.disableUniformBuffers = false;
  10306. this._uniformBuffers = new Array();
  10307. // Observables
  10308. /**
  10309. * Observable raised when the engine begins a new frame
  10310. */
  10311. this.onBeginFrameObservable = new BABYLON.Observable();
  10312. /**
  10313. * Observable raised when the engine ends the current frame
  10314. */
  10315. this.onEndFrameObservable = new BABYLON.Observable();
  10316. /**
  10317. * Observable raised when the engine is about to compile a shader
  10318. */
  10319. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10320. /**
  10321. * Observable raised when the engine has jsut compiled a shader
  10322. */
  10323. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10324. this._windowIsBackground = false;
  10325. this._webGLVersion = 1.0;
  10326. this._badOS = false;
  10327. this._badDesktopOS = false;
  10328. /**
  10329. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10330. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10331. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10332. */
  10333. this.disableTextureBindingOptimization = false;
  10334. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10335. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10336. this.onVRRequestPresentStart = new BABYLON.Observable();
  10337. this._colorWrite = true;
  10338. this._drawCalls = new BABYLON.PerfCounter();
  10339. this._textureCollisions = new BABYLON.PerfCounter();
  10340. this._renderingQueueLaunched = false;
  10341. this._activeRenderLoops = new Array();
  10342. // Deterministic lockstepMaxSteps
  10343. this._deterministicLockstep = false;
  10344. this._lockstepMaxSteps = 4;
  10345. // Lost context
  10346. this.onContextLostObservable = new BABYLON.Observable();
  10347. this.onContextRestoredObservable = new BABYLON.Observable();
  10348. this._contextWasLost = false;
  10349. this._doNotHandleContextLost = false;
  10350. // FPS
  10351. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10352. this._fps = 60;
  10353. this._deltaTime = 0;
  10354. /**
  10355. * Turn this value on if you want to pause FPS computation when in background
  10356. */
  10357. this.disablePerformanceMonitorInBackground = false;
  10358. // States
  10359. this._depthCullingState = new BABYLON._DepthCullingState();
  10360. this._stencilState = new BABYLON._StencilState();
  10361. this._alphaState = new BABYLON._AlphaState();
  10362. this._alphaMode = Engine.ALPHA_DISABLE;
  10363. // Cache
  10364. this._internalTexturesCache = new Array();
  10365. this._activeChannel = 0;
  10366. this._currentTextureChannel = -1;
  10367. this._boundTexturesCache = {};
  10368. this._compiledEffects = {};
  10369. this._vertexAttribArraysEnabled = [];
  10370. this._uintIndicesCurrentlySet = false;
  10371. this._currentBoundBuffer = new Array();
  10372. this._currentBufferPointers = new Array();
  10373. this._currentInstanceLocations = new Array();
  10374. this._currentInstanceBuffers = new Array();
  10375. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10376. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10377. this._vaoRecordInProgress = false;
  10378. this._mustWipeVertexAttributes = false;
  10379. this._nextFreeTextureSlots = new Array();
  10380. this._maxSimultaneousTextures = 0;
  10381. this._activeRequests = new Array();
  10382. // Hardware supported Compressed Textures
  10383. this._texturesSupported = new Array();
  10384. this._onVRFullScreenTriggered = function () {
  10385. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10386. //get the old size before we change
  10387. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10388. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10389. //get the width and height, change the render size
  10390. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10391. _this.setHardwareScalingLevel(1);
  10392. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10393. }
  10394. else {
  10395. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10396. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10397. }
  10398. };
  10399. this._boundUniforms = {};
  10400. // Register promises
  10401. BABYLON.PromisePolyfill.Apply();
  10402. var canvas = null;
  10403. Engine.Instances.push(this);
  10404. if (!canvasOrContext) {
  10405. return;
  10406. }
  10407. options = options || {};
  10408. if (canvasOrContext.getContext) {
  10409. canvas = canvasOrContext;
  10410. this._renderingCanvas = canvas;
  10411. if (antialias != null) {
  10412. options.antialias = antialias;
  10413. }
  10414. if (options.deterministicLockstep === undefined) {
  10415. options.deterministicLockstep = false;
  10416. }
  10417. if (options.lockstepMaxSteps === undefined) {
  10418. options.lockstepMaxSteps = 4;
  10419. }
  10420. if (options.preserveDrawingBuffer === undefined) {
  10421. options.preserveDrawingBuffer = false;
  10422. }
  10423. if (options.audioEngine === undefined) {
  10424. options.audioEngine = true;
  10425. }
  10426. if (options.stencil === undefined) {
  10427. options.stencil = true;
  10428. }
  10429. this._deterministicLockstep = options.deterministicLockstep;
  10430. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10431. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10432. // Exceptions
  10433. if (navigator && navigator.userAgent) {
  10434. var ua = navigator.userAgent;
  10435. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10436. var exception = _a[_i];
  10437. var key = exception.key;
  10438. var targets = exception.targets;
  10439. if (ua.indexOf(key) > -1) {
  10440. if (exception.capture && exception.captureConstraint) {
  10441. var capture = exception.capture;
  10442. var constraint = exception.captureConstraint;
  10443. var regex = new RegExp(capture);
  10444. var matches = regex.exec(ua);
  10445. if (matches && matches.length > 0) {
  10446. var capturedValue = parseInt(matches[matches.length - 1]);
  10447. if (capturedValue >= constraint) {
  10448. continue;
  10449. }
  10450. }
  10451. }
  10452. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10453. var target = targets_1[_b];
  10454. switch (target) {
  10455. case "uniformBuffer":
  10456. this.disableUniformBuffers = true;
  10457. break;
  10458. case "textureBindingOptimization":
  10459. this.disableTextureBindingOptimization = true;
  10460. break;
  10461. }
  10462. }
  10463. break;
  10464. }
  10465. }
  10466. }
  10467. // GL
  10468. if (!options.disableWebGL2Support) {
  10469. try {
  10470. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10471. if (this._gl) {
  10472. this._webGLVersion = 2.0;
  10473. }
  10474. }
  10475. catch (e) {
  10476. // Do nothing
  10477. }
  10478. }
  10479. if (!this._gl) {
  10480. if (!canvas) {
  10481. throw new Error("The provided canvas is null or undefined.");
  10482. }
  10483. try {
  10484. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10485. }
  10486. catch (e) {
  10487. throw new Error("WebGL not supported");
  10488. }
  10489. }
  10490. if (!this._gl) {
  10491. throw new Error("WebGL not supported");
  10492. }
  10493. this._onCanvasFocus = function () {
  10494. _this.onCanvasFocusObservable.notifyObservers(_this);
  10495. };
  10496. this._onCanvasBlur = function () {
  10497. _this.onCanvasBlurObservable.notifyObservers(_this);
  10498. };
  10499. canvas.addEventListener("focus", this._onCanvasFocus);
  10500. canvas.addEventListener("blur", this._onCanvasBlur);
  10501. this._onBlur = function () {
  10502. if (_this.disablePerformanceMonitorInBackground) {
  10503. _this._performanceMonitor.disable();
  10504. }
  10505. _this._windowIsBackground = true;
  10506. };
  10507. this._onFocus = function () {
  10508. if (_this.disablePerformanceMonitorInBackground) {
  10509. _this._performanceMonitor.enable();
  10510. }
  10511. _this._windowIsBackground = false;
  10512. };
  10513. this._onCanvasPointerOut = function (ev) {
  10514. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10515. };
  10516. window.addEventListener("blur", this._onBlur);
  10517. window.addEventListener("focus", this._onFocus);
  10518. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10519. // Context lost
  10520. if (!this._doNotHandleContextLost) {
  10521. this._onContextLost = function (evt) {
  10522. evt.preventDefault();
  10523. _this._contextWasLost = true;
  10524. BABYLON.Tools.Warn("WebGL context lost.");
  10525. _this.onContextLostObservable.notifyObservers(_this);
  10526. };
  10527. this._onContextRestored = function (evt) {
  10528. // Adding a timeout to avoid race condition at browser level
  10529. setTimeout(function () {
  10530. // Rebuild gl context
  10531. _this._initGLContext();
  10532. // Rebuild effects
  10533. _this._rebuildEffects();
  10534. // Rebuild textures
  10535. _this._rebuildInternalTextures();
  10536. // Rebuild buffers
  10537. _this._rebuildBuffers();
  10538. // Cache
  10539. _this.wipeCaches(true);
  10540. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10541. _this.onContextRestoredObservable.notifyObservers(_this);
  10542. _this._contextWasLost = false;
  10543. }, 0);
  10544. };
  10545. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10546. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10547. }
  10548. }
  10549. else {
  10550. this._gl = canvasOrContext;
  10551. this._renderingCanvas = this._gl.canvas;
  10552. if (this._gl.renderbufferStorageMultisample) {
  10553. this._webGLVersion = 2.0;
  10554. }
  10555. options.stencil = this._gl.getContextAttributes().stencil;
  10556. }
  10557. // Viewport
  10558. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10559. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10560. this.resize();
  10561. this._isStencilEnable = options.stencil ? true : false;
  10562. this._initGLContext();
  10563. if (canvas) {
  10564. // Fullscreen
  10565. this._onFullscreenChange = function () {
  10566. if (document.fullscreen !== undefined) {
  10567. _this.isFullscreen = document.fullscreen;
  10568. }
  10569. else if (document.mozFullScreen !== undefined) {
  10570. _this.isFullscreen = document.mozFullScreen;
  10571. }
  10572. else if (document.webkitIsFullScreen !== undefined) {
  10573. _this.isFullscreen = document.webkitIsFullScreen;
  10574. }
  10575. else if (document.msIsFullScreen !== undefined) {
  10576. _this.isFullscreen = document.msIsFullScreen;
  10577. }
  10578. // Pointer lock
  10579. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10580. canvas.requestPointerLock = canvas.requestPointerLock ||
  10581. canvas.msRequestPointerLock ||
  10582. canvas.mozRequestPointerLock ||
  10583. canvas.webkitRequestPointerLock;
  10584. if (canvas.requestPointerLock) {
  10585. canvas.requestPointerLock();
  10586. }
  10587. }
  10588. };
  10589. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10590. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10591. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10592. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10593. // Pointer lock
  10594. this._onPointerLockChange = function () {
  10595. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10596. document.webkitPointerLockElement === canvas ||
  10597. document.msPointerLockElement === canvas ||
  10598. document.pointerLockElement === canvas);
  10599. };
  10600. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10601. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10602. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10603. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10604. this._onVRDisplayPointerRestricted = function () {
  10605. if (canvas) {
  10606. canvas.requestPointerLock();
  10607. }
  10608. };
  10609. this._onVRDisplayPointerUnrestricted = function () {
  10610. document.exitPointerLock();
  10611. };
  10612. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10613. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10614. }
  10615. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10616. Engine.audioEngine = new BABYLON.AudioEngine();
  10617. }
  10618. // Prepare buffer pointers
  10619. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10620. this._currentBufferPointers[i] = new BufferPointer();
  10621. }
  10622. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10623. // Load WebVR Devices
  10624. if (options.autoEnableWebVR) {
  10625. this.initWebVR();
  10626. }
  10627. // Detect if we are running on a faulty buggy OS.
  10628. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10629. // Detect if we are running on a faulty buggy desktop OS.
  10630. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10631. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  10632. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10633. }
  10634. Object.defineProperty(Engine, "LastCreatedEngine", {
  10635. get: function () {
  10636. if (Engine.Instances.length === 0) {
  10637. return null;
  10638. }
  10639. return Engine.Instances[Engine.Instances.length - 1];
  10640. },
  10641. enumerable: true,
  10642. configurable: true
  10643. });
  10644. Object.defineProperty(Engine, "LastCreatedScene", {
  10645. get: function () {
  10646. var lastCreatedEngine = Engine.LastCreatedEngine;
  10647. if (!lastCreatedEngine) {
  10648. return null;
  10649. }
  10650. if (lastCreatedEngine.scenes.length === 0) {
  10651. return null;
  10652. }
  10653. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10654. },
  10655. enumerable: true,
  10656. configurable: true
  10657. });
  10658. /**
  10659. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10660. */
  10661. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10662. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10663. var engine = Engine.Instances[engineIndex];
  10664. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10665. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10666. }
  10667. }
  10668. };
  10669. Object.defineProperty(Engine, "NEVER", {
  10670. get: function () {
  10671. return Engine._NEVER;
  10672. },
  10673. enumerable: true,
  10674. configurable: true
  10675. });
  10676. Object.defineProperty(Engine, "ALWAYS", {
  10677. get: function () {
  10678. return Engine._ALWAYS;
  10679. },
  10680. enumerable: true,
  10681. configurable: true
  10682. });
  10683. Object.defineProperty(Engine, "LESS", {
  10684. get: function () {
  10685. return Engine._LESS;
  10686. },
  10687. enumerable: true,
  10688. configurable: true
  10689. });
  10690. Object.defineProperty(Engine, "EQUAL", {
  10691. get: function () {
  10692. return Engine._EQUAL;
  10693. },
  10694. enumerable: true,
  10695. configurable: true
  10696. });
  10697. Object.defineProperty(Engine, "LEQUAL", {
  10698. get: function () {
  10699. return Engine._LEQUAL;
  10700. },
  10701. enumerable: true,
  10702. configurable: true
  10703. });
  10704. Object.defineProperty(Engine, "GREATER", {
  10705. get: function () {
  10706. return Engine._GREATER;
  10707. },
  10708. enumerable: true,
  10709. configurable: true
  10710. });
  10711. Object.defineProperty(Engine, "GEQUAL", {
  10712. get: function () {
  10713. return Engine._GEQUAL;
  10714. },
  10715. enumerable: true,
  10716. configurable: true
  10717. });
  10718. Object.defineProperty(Engine, "NOTEQUAL", {
  10719. get: function () {
  10720. return Engine._NOTEQUAL;
  10721. },
  10722. enumerable: true,
  10723. configurable: true
  10724. });
  10725. Object.defineProperty(Engine, "KEEP", {
  10726. get: function () {
  10727. return Engine._KEEP;
  10728. },
  10729. enumerable: true,
  10730. configurable: true
  10731. });
  10732. Object.defineProperty(Engine, "REPLACE", {
  10733. get: function () {
  10734. return Engine._REPLACE;
  10735. },
  10736. enumerable: true,
  10737. configurable: true
  10738. });
  10739. Object.defineProperty(Engine, "INCR", {
  10740. get: function () {
  10741. return Engine._INCR;
  10742. },
  10743. enumerable: true,
  10744. configurable: true
  10745. });
  10746. Object.defineProperty(Engine, "DECR", {
  10747. get: function () {
  10748. return Engine._DECR;
  10749. },
  10750. enumerable: true,
  10751. configurable: true
  10752. });
  10753. Object.defineProperty(Engine, "INVERT", {
  10754. get: function () {
  10755. return Engine._INVERT;
  10756. },
  10757. enumerable: true,
  10758. configurable: true
  10759. });
  10760. Object.defineProperty(Engine, "INCR_WRAP", {
  10761. get: function () {
  10762. return Engine._INCR_WRAP;
  10763. },
  10764. enumerable: true,
  10765. configurable: true
  10766. });
  10767. Object.defineProperty(Engine, "DECR_WRAP", {
  10768. get: function () {
  10769. return Engine._DECR_WRAP;
  10770. },
  10771. enumerable: true,
  10772. configurable: true
  10773. });
  10774. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10775. get: function () {
  10776. return Engine._ALPHA_DISABLE;
  10777. },
  10778. enumerable: true,
  10779. configurable: true
  10780. });
  10781. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10782. get: function () {
  10783. return Engine._ALPHA_ONEONE;
  10784. },
  10785. enumerable: true,
  10786. configurable: true
  10787. });
  10788. Object.defineProperty(Engine, "ALPHA_ADD", {
  10789. get: function () {
  10790. return Engine._ALPHA_ADD;
  10791. },
  10792. enumerable: true,
  10793. configurable: true
  10794. });
  10795. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10796. get: function () {
  10797. return Engine._ALPHA_COMBINE;
  10798. },
  10799. enumerable: true,
  10800. configurable: true
  10801. });
  10802. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10803. get: function () {
  10804. return Engine._ALPHA_SUBTRACT;
  10805. },
  10806. enumerable: true,
  10807. configurable: true
  10808. });
  10809. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10810. get: function () {
  10811. return Engine._ALPHA_MULTIPLY;
  10812. },
  10813. enumerable: true,
  10814. configurable: true
  10815. });
  10816. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10817. get: function () {
  10818. return Engine._ALPHA_MAXIMIZED;
  10819. },
  10820. enumerable: true,
  10821. configurable: true
  10822. });
  10823. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  10824. get: function () {
  10825. return Engine._ALPHA_PREMULTIPLIED;
  10826. },
  10827. enumerable: true,
  10828. configurable: true
  10829. });
  10830. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  10831. get: function () {
  10832. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  10833. },
  10834. enumerable: true,
  10835. configurable: true
  10836. });
  10837. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  10838. get: function () {
  10839. return Engine._ALPHA_INTERPOLATE;
  10840. },
  10841. enumerable: true,
  10842. configurable: true
  10843. });
  10844. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  10845. get: function () {
  10846. return Engine._ALPHA_SCREENMODE;
  10847. },
  10848. enumerable: true,
  10849. configurable: true
  10850. });
  10851. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  10852. get: function () {
  10853. return Engine._DELAYLOADSTATE_NONE;
  10854. },
  10855. enumerable: true,
  10856. configurable: true
  10857. });
  10858. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  10859. get: function () {
  10860. return Engine._DELAYLOADSTATE_LOADED;
  10861. },
  10862. enumerable: true,
  10863. configurable: true
  10864. });
  10865. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10866. get: function () {
  10867. return Engine._DELAYLOADSTATE_LOADING;
  10868. },
  10869. enumerable: true,
  10870. configurable: true
  10871. });
  10872. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10873. get: function () {
  10874. return Engine._DELAYLOADSTATE_NOTLOADED;
  10875. },
  10876. enumerable: true,
  10877. configurable: true
  10878. });
  10879. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10880. get: function () {
  10881. return Engine._TEXTUREFORMAT_ALPHA;
  10882. },
  10883. enumerable: true,
  10884. configurable: true
  10885. });
  10886. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10887. get: function () {
  10888. return Engine._TEXTUREFORMAT_LUMINANCE;
  10889. },
  10890. enumerable: true,
  10891. configurable: true
  10892. });
  10893. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  10894. /**
  10895. * R32F
  10896. */
  10897. get: function () {
  10898. return Engine._TEXTUREFORMAT_R32F;
  10899. },
  10900. enumerable: true,
  10901. configurable: true
  10902. });
  10903. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  10904. /**
  10905. * RG32F
  10906. */
  10907. get: function () {
  10908. return Engine._TEXTUREFORMAT_RG32F;
  10909. },
  10910. enumerable: true,
  10911. configurable: true
  10912. });
  10913. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  10914. /**
  10915. * RGB32F
  10916. */
  10917. get: function () {
  10918. return Engine._TEXTUREFORMAT_RGB32F;
  10919. },
  10920. enumerable: true,
  10921. configurable: true
  10922. });
  10923. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  10924. /**
  10925. * RGBA32F
  10926. */
  10927. get: function () {
  10928. return Engine._TEXTUREFORMAT_RGBA32F;
  10929. },
  10930. enumerable: true,
  10931. configurable: true
  10932. });
  10933. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  10934. get: function () {
  10935. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  10936. },
  10937. enumerable: true,
  10938. configurable: true
  10939. });
  10940. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  10941. get: function () {
  10942. return Engine._TEXTUREFORMAT_RGB;
  10943. },
  10944. enumerable: true,
  10945. configurable: true
  10946. });
  10947. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  10948. get: function () {
  10949. return Engine._TEXTUREFORMAT_RGBA;
  10950. },
  10951. enumerable: true,
  10952. configurable: true
  10953. });
  10954. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  10955. get: function () {
  10956. return Engine._TEXTURETYPE_UNSIGNED_INT;
  10957. },
  10958. enumerable: true,
  10959. configurable: true
  10960. });
  10961. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  10962. get: function () {
  10963. return Engine._TEXTURETYPE_FLOAT;
  10964. },
  10965. enumerable: true,
  10966. configurable: true
  10967. });
  10968. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  10969. get: function () {
  10970. return Engine._TEXTURETYPE_HALF_FLOAT;
  10971. },
  10972. enumerable: true,
  10973. configurable: true
  10974. });
  10975. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  10976. get: function () {
  10977. return Engine._SCALEMODE_FLOOR;
  10978. },
  10979. enumerable: true,
  10980. configurable: true
  10981. });
  10982. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  10983. get: function () {
  10984. return Engine._SCALEMODE_NEAREST;
  10985. },
  10986. enumerable: true,
  10987. configurable: true
  10988. });
  10989. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  10990. get: function () {
  10991. return Engine._SCALEMODE_CEILING;
  10992. },
  10993. enumerable: true,
  10994. configurable: true
  10995. });
  10996. Object.defineProperty(Engine, "Version", {
  10997. get: function () {
  10998. return "3.2.0-alpha10";
  10999. },
  11000. enumerable: true,
  11001. configurable: true
  11002. });
  11003. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11004. get: function () {
  11005. return this._vrExclusivePointerMode;
  11006. },
  11007. enumerable: true,
  11008. configurable: true
  11009. });
  11010. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11011. get: function () {
  11012. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11013. },
  11014. enumerable: true,
  11015. configurable: true
  11016. });
  11017. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11018. get: function () {
  11019. return this._webGLVersion < 2 || this.forcePOTTextures;
  11020. },
  11021. enumerable: true,
  11022. configurable: true
  11023. });
  11024. Object.defineProperty(Engine.prototype, "badOS", {
  11025. get: function () {
  11026. return this._badOS;
  11027. },
  11028. enumerable: true,
  11029. configurable: true
  11030. });
  11031. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11032. get: function () {
  11033. return this._badDesktopOS;
  11034. },
  11035. enumerable: true,
  11036. configurable: true
  11037. });
  11038. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11039. get: function () {
  11040. return this._performanceMonitor;
  11041. },
  11042. enumerable: true,
  11043. configurable: true
  11044. });
  11045. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11046. get: function () {
  11047. return this._texturesSupported;
  11048. },
  11049. enumerable: true,
  11050. configurable: true
  11051. });
  11052. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11053. get: function () {
  11054. return this._textureFormatInUse;
  11055. },
  11056. enumerable: true,
  11057. configurable: true
  11058. });
  11059. Object.defineProperty(Engine.prototype, "currentViewport", {
  11060. get: function () {
  11061. return this._cachedViewport;
  11062. },
  11063. enumerable: true,
  11064. configurable: true
  11065. });
  11066. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11067. // Empty texture
  11068. get: function () {
  11069. if (!this._emptyTexture) {
  11070. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11071. }
  11072. return this._emptyTexture;
  11073. },
  11074. enumerable: true,
  11075. configurable: true
  11076. });
  11077. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11078. get: function () {
  11079. if (!this._emptyTexture3D) {
  11080. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11081. }
  11082. return this._emptyTexture3D;
  11083. },
  11084. enumerable: true,
  11085. configurable: true
  11086. });
  11087. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11088. get: function () {
  11089. if (!this._emptyCubeTexture) {
  11090. var faceData = new Uint8Array(4);
  11091. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11092. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11093. }
  11094. return this._emptyCubeTexture;
  11095. },
  11096. enumerable: true,
  11097. configurable: true
  11098. });
  11099. Engine.prototype._rebuildInternalTextures = function () {
  11100. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11101. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11102. var internalTexture = currentState_1[_i];
  11103. internalTexture._rebuild();
  11104. }
  11105. };
  11106. Engine.prototype._rebuildEffects = function () {
  11107. for (var key in this._compiledEffects) {
  11108. var effect = this._compiledEffects[key];
  11109. effect._prepareEffect();
  11110. }
  11111. BABYLON.Effect.ResetCache();
  11112. };
  11113. Engine.prototype._rebuildBuffers = function () {
  11114. // Index / Vertex
  11115. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11116. var scene = _a[_i];
  11117. scene.resetCachedMaterial();
  11118. scene._rebuildGeometries();
  11119. scene._rebuildTextures();
  11120. }
  11121. // Uniforms
  11122. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11123. var uniformBuffer = _c[_b];
  11124. uniformBuffer._rebuild();
  11125. }
  11126. };
  11127. Engine.prototype._initGLContext = function () {
  11128. // Caps
  11129. this._caps = new EngineCapabilities();
  11130. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11131. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11132. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11133. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11134. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11135. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11136. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11137. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11138. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11139. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11140. // Infos
  11141. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11142. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11143. if (rendererInfo != null) {
  11144. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11145. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11146. }
  11147. if (!this._glVendor) {
  11148. this._glVendor = "Unknown vendor";
  11149. }
  11150. if (!this._glRenderer) {
  11151. this._glRenderer = "Unknown renderer";
  11152. }
  11153. // Constants
  11154. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11155. if (this._gl.RGBA16F !== 0x881A) {
  11156. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11157. }
  11158. if (this._gl.RGBA32F !== 0x8814) {
  11159. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11160. }
  11161. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11162. this._gl.DEPTH24_STENCIL8 = 35056;
  11163. }
  11164. // Extensions
  11165. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11166. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11167. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11168. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11169. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11170. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11171. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11172. 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');
  11173. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11174. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11175. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11176. this._caps.highPrecisionShaderSupported = true;
  11177. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11178. if (this._caps.timerQuery) {
  11179. if (this._webGLVersion === 1) {
  11180. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11181. }
  11182. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11183. }
  11184. // Checks if some of the format renders first to allow the use of webgl inspector.
  11185. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11186. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  11187. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  11188. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  11189. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  11190. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  11191. if (this._webGLVersion > 1) {
  11192. this._gl.HALF_FLOAT_OES = 0x140B;
  11193. }
  11194. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11195. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  11196. // Draw buffers
  11197. if (this._webGLVersion > 1) {
  11198. this._caps.drawBuffersExtension = true;
  11199. }
  11200. else {
  11201. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11202. if (drawBuffersExtension !== null) {
  11203. this._caps.drawBuffersExtension = true;
  11204. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11205. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11206. for (var i = 0; i < 16; i++) {
  11207. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11208. }
  11209. }
  11210. else {
  11211. this._caps.drawBuffersExtension = false;
  11212. }
  11213. }
  11214. // Depth Texture
  11215. if (this._webGLVersion > 1) {
  11216. this._caps.depthTextureExtension = true;
  11217. }
  11218. else {
  11219. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11220. if (depthTextureExtension != null) {
  11221. this._caps.depthTextureExtension = true;
  11222. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11223. }
  11224. }
  11225. // Vertex array object
  11226. if (this._webGLVersion > 1) {
  11227. this._caps.vertexArrayObject = true;
  11228. }
  11229. else {
  11230. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11231. if (vertexArrayObjectExtension != null) {
  11232. this._caps.vertexArrayObject = true;
  11233. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11234. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11235. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11236. }
  11237. else {
  11238. this._caps.vertexArrayObject = false;
  11239. }
  11240. }
  11241. // Instances count
  11242. if (this._webGLVersion > 1) {
  11243. this._caps.instancedArrays = true;
  11244. }
  11245. else {
  11246. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11247. if (instanceExtension != null) {
  11248. this._caps.instancedArrays = true;
  11249. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11250. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11251. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11252. }
  11253. else {
  11254. this._caps.instancedArrays = false;
  11255. }
  11256. }
  11257. // Intelligently add supported compressed formats in order to check for.
  11258. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11259. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11260. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11261. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11262. if (this._caps.astc)
  11263. this.texturesSupported.push('-astc.ktx');
  11264. if (this._caps.s3tc)
  11265. this.texturesSupported.push('-dxt.ktx');
  11266. if (this._caps.pvrtc)
  11267. this.texturesSupported.push('-pvrtc.ktx');
  11268. if (this._caps.etc2)
  11269. this.texturesSupported.push('-etc2.ktx');
  11270. if (this._caps.etc1)
  11271. this.texturesSupported.push('-etc1.ktx');
  11272. if (this._gl.getShaderPrecisionFormat) {
  11273. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11274. if (highp) {
  11275. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11276. }
  11277. }
  11278. // Depth buffer
  11279. this.setDepthBuffer(true);
  11280. this.setDepthFunctionToLessOrEqual();
  11281. this.setDepthWrite(true);
  11282. // Texture maps
  11283. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11284. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11285. this._nextFreeTextureSlots.push(slot);
  11286. }
  11287. };
  11288. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11289. get: function () {
  11290. return this._webGLVersion;
  11291. },
  11292. enumerable: true,
  11293. configurable: true
  11294. });
  11295. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11296. /**
  11297. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11298. */
  11299. get: function () {
  11300. return this._isStencilEnable;
  11301. },
  11302. enumerable: true,
  11303. configurable: true
  11304. });
  11305. Engine.prototype._prepareWorkingCanvas = function () {
  11306. if (this._workingCanvas) {
  11307. return;
  11308. }
  11309. this._workingCanvas = document.createElement("canvas");
  11310. var context = this._workingCanvas.getContext("2d");
  11311. if (context) {
  11312. this._workingContext = context;
  11313. }
  11314. };
  11315. Engine.prototype.resetTextureCache = function () {
  11316. for (var key in this._boundTexturesCache) {
  11317. var boundTexture = this._boundTexturesCache[key];
  11318. if (boundTexture) {
  11319. this._removeDesignatedSlot(boundTexture);
  11320. }
  11321. this._boundTexturesCache[key] = null;
  11322. }
  11323. if (!this.disableTextureBindingOptimization) {
  11324. this._nextFreeTextureSlots = [];
  11325. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11326. this._nextFreeTextureSlots.push(slot);
  11327. }
  11328. }
  11329. this._currentTextureChannel = -1;
  11330. };
  11331. Engine.prototype.isDeterministicLockStep = function () {
  11332. return this._deterministicLockstep;
  11333. };
  11334. Engine.prototype.getLockstepMaxSteps = function () {
  11335. return this._lockstepMaxSteps;
  11336. };
  11337. Engine.prototype.getGlInfo = function () {
  11338. return {
  11339. vendor: this._glVendor,
  11340. renderer: this._glRenderer,
  11341. version: this._glVersion
  11342. };
  11343. };
  11344. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11345. if (useScreen === void 0) { useScreen = false; }
  11346. var viewport = camera.viewport;
  11347. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11348. };
  11349. Engine.prototype.getRenderWidth = function (useScreen) {
  11350. if (useScreen === void 0) { useScreen = false; }
  11351. if (!useScreen && this._currentRenderTarget) {
  11352. return this._currentRenderTarget.width;
  11353. }
  11354. return this._gl.drawingBufferWidth;
  11355. };
  11356. Engine.prototype.getRenderHeight = function (useScreen) {
  11357. if (useScreen === void 0) { useScreen = false; }
  11358. if (!useScreen && this._currentRenderTarget) {
  11359. return this._currentRenderTarget.height;
  11360. }
  11361. return this._gl.drawingBufferHeight;
  11362. };
  11363. Engine.prototype.getRenderingCanvas = function () {
  11364. return this._renderingCanvas;
  11365. };
  11366. Engine.prototype.getRenderingCanvasClientRect = function () {
  11367. if (!this._renderingCanvas) {
  11368. return null;
  11369. }
  11370. return this._renderingCanvas.getBoundingClientRect();
  11371. };
  11372. Engine.prototype.setHardwareScalingLevel = function (level) {
  11373. this._hardwareScalingLevel = level;
  11374. this.resize();
  11375. };
  11376. Engine.prototype.getHardwareScalingLevel = function () {
  11377. return this._hardwareScalingLevel;
  11378. };
  11379. Engine.prototype.getLoadedTexturesCache = function () {
  11380. return this._internalTexturesCache;
  11381. };
  11382. Engine.prototype.getCaps = function () {
  11383. return this._caps;
  11384. };
  11385. Object.defineProperty(Engine.prototype, "drawCalls", {
  11386. /** The number of draw calls submitted last frame */
  11387. get: function () {
  11388. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11389. return 0;
  11390. },
  11391. enumerable: true,
  11392. configurable: true
  11393. });
  11394. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11395. get: function () {
  11396. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11397. return null;
  11398. },
  11399. enumerable: true,
  11400. configurable: true
  11401. });
  11402. Engine.prototype.getDepthFunction = function () {
  11403. return this._depthCullingState.depthFunc;
  11404. };
  11405. Engine.prototype.setDepthFunction = function (depthFunc) {
  11406. this._depthCullingState.depthFunc = depthFunc;
  11407. };
  11408. Engine.prototype.setDepthFunctionToGreater = function () {
  11409. this._depthCullingState.depthFunc = this._gl.GREATER;
  11410. };
  11411. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11412. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11413. };
  11414. Engine.prototype.setDepthFunctionToLess = function () {
  11415. this._depthCullingState.depthFunc = this._gl.LESS;
  11416. };
  11417. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11418. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11419. };
  11420. Engine.prototype.getStencilBuffer = function () {
  11421. return this._stencilState.stencilTest;
  11422. };
  11423. Engine.prototype.setStencilBuffer = function (enable) {
  11424. this._stencilState.stencilTest = enable;
  11425. };
  11426. Engine.prototype.getStencilMask = function () {
  11427. return this._stencilState.stencilMask;
  11428. };
  11429. Engine.prototype.setStencilMask = function (mask) {
  11430. this._stencilState.stencilMask = mask;
  11431. };
  11432. Engine.prototype.getStencilFunction = function () {
  11433. return this._stencilState.stencilFunc;
  11434. };
  11435. Engine.prototype.getStencilFunctionReference = function () {
  11436. return this._stencilState.stencilFuncRef;
  11437. };
  11438. Engine.prototype.getStencilFunctionMask = function () {
  11439. return this._stencilState.stencilFuncMask;
  11440. };
  11441. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11442. this._stencilState.stencilFunc = stencilFunc;
  11443. };
  11444. Engine.prototype.setStencilFunctionReference = function (reference) {
  11445. this._stencilState.stencilFuncRef = reference;
  11446. };
  11447. Engine.prototype.setStencilFunctionMask = function (mask) {
  11448. this._stencilState.stencilFuncMask = mask;
  11449. };
  11450. Engine.prototype.getStencilOperationFail = function () {
  11451. return this._stencilState.stencilOpStencilFail;
  11452. };
  11453. Engine.prototype.getStencilOperationDepthFail = function () {
  11454. return this._stencilState.stencilOpDepthFail;
  11455. };
  11456. Engine.prototype.getStencilOperationPass = function () {
  11457. return this._stencilState.stencilOpStencilDepthPass;
  11458. };
  11459. Engine.prototype.setStencilOperationFail = function (operation) {
  11460. this._stencilState.stencilOpStencilFail = operation;
  11461. };
  11462. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11463. this._stencilState.stencilOpDepthFail = operation;
  11464. };
  11465. Engine.prototype.setStencilOperationPass = function (operation) {
  11466. this._stencilState.stencilOpStencilDepthPass = operation;
  11467. };
  11468. Engine.prototype.setDitheringState = function (value) {
  11469. if (value) {
  11470. this._gl.enable(this._gl.DITHER);
  11471. }
  11472. else {
  11473. this._gl.disable(this._gl.DITHER);
  11474. }
  11475. };
  11476. Engine.prototype.setRasterizerState = function (value) {
  11477. if (value) {
  11478. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11479. }
  11480. else {
  11481. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11482. }
  11483. };
  11484. /**
  11485. * stop executing a render loop function and remove it from the execution array
  11486. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11487. */
  11488. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11489. if (!renderFunction) {
  11490. this._activeRenderLoops = [];
  11491. return;
  11492. }
  11493. var index = this._activeRenderLoops.indexOf(renderFunction);
  11494. if (index >= 0) {
  11495. this._activeRenderLoops.splice(index, 1);
  11496. }
  11497. };
  11498. Engine.prototype._renderLoop = function () {
  11499. if (!this._contextWasLost) {
  11500. var shouldRender = true;
  11501. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11502. shouldRender = false;
  11503. }
  11504. if (shouldRender) {
  11505. // Start new frame
  11506. this.beginFrame();
  11507. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11508. var renderFunction = this._activeRenderLoops[index];
  11509. renderFunction();
  11510. }
  11511. // Present
  11512. this.endFrame();
  11513. }
  11514. }
  11515. if (this._activeRenderLoops.length > 0) {
  11516. // Register new frame
  11517. var requester = null;
  11518. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11519. requester = this._vrDisplay;
  11520. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11521. }
  11522. else {
  11523. this._renderingQueueLaunched = false;
  11524. }
  11525. };
  11526. /**
  11527. * Register and execute a render loop. The engine can have more than one render function.
  11528. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11529. * @example
  11530. * engine.runRenderLoop(function () {
  11531. * scene.render()
  11532. * })
  11533. */
  11534. Engine.prototype.runRenderLoop = function (renderFunction) {
  11535. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11536. return;
  11537. }
  11538. this._activeRenderLoops.push(renderFunction);
  11539. if (!this._renderingQueueLaunched) {
  11540. this._renderingQueueLaunched = true;
  11541. this._bindedRenderFunction = this._renderLoop.bind(this);
  11542. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11543. }
  11544. };
  11545. /**
  11546. * Toggle full screen mode.
  11547. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11548. * @param {any} options - an options object to be sent to the requestFullscreen function
  11549. */
  11550. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11551. if (this.isFullscreen) {
  11552. BABYLON.Tools.ExitFullscreen();
  11553. }
  11554. else {
  11555. this._pointerLockRequested = requestPointerLock;
  11556. if (this._renderingCanvas) {
  11557. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11558. }
  11559. }
  11560. };
  11561. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11562. if (stencil === void 0) { stencil = false; }
  11563. this.applyStates();
  11564. var mode = 0;
  11565. if (backBuffer && color) {
  11566. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11567. mode |= this._gl.COLOR_BUFFER_BIT;
  11568. }
  11569. if (depth) {
  11570. this._gl.clearDepth(1.0);
  11571. mode |= this._gl.DEPTH_BUFFER_BIT;
  11572. }
  11573. if (stencil) {
  11574. this._gl.clearStencil(0);
  11575. mode |= this._gl.STENCIL_BUFFER_BIT;
  11576. }
  11577. this._gl.clear(mode);
  11578. };
  11579. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11580. var gl = this._gl;
  11581. // Save state
  11582. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11583. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11584. // Change state
  11585. gl.enable(gl.SCISSOR_TEST);
  11586. gl.scissor(x, y, width, height);
  11587. // Clear
  11588. this.clear(clearColor, true, true, true);
  11589. // Restore state
  11590. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11591. if (curScissor === true) {
  11592. gl.enable(gl.SCISSOR_TEST);
  11593. }
  11594. else {
  11595. gl.disable(gl.SCISSOR_TEST);
  11596. }
  11597. };
  11598. /**
  11599. * Set the WebGL's viewport
  11600. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11601. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11602. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11603. */
  11604. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11605. var width = requiredWidth || this.getRenderWidth();
  11606. var height = requiredHeight || this.getRenderHeight();
  11607. var x = viewport.x || 0;
  11608. var y = viewport.y || 0;
  11609. this._cachedViewport = viewport;
  11610. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11611. };
  11612. /**
  11613. * Directly set the WebGL Viewport
  11614. * The x, y, width & height are directly passed to the WebGL call
  11615. * @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.
  11616. */
  11617. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11618. var currentViewport = this._cachedViewport;
  11619. this._cachedViewport = null;
  11620. this._gl.viewport(x, y, width, height);
  11621. return currentViewport;
  11622. };
  11623. Engine.prototype.beginFrame = function () {
  11624. this.onBeginFrameObservable.notifyObservers(this);
  11625. this._measureFps();
  11626. };
  11627. Engine.prototype.endFrame = function () {
  11628. //force a flush in case we are using a bad OS.
  11629. if (this._badOS) {
  11630. this.flushFramebuffer();
  11631. }
  11632. //submit frame to the vr device, if enabled
  11633. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11634. // TODO: We should only submit the frame if we read frameData successfully.
  11635. this._vrDisplay.submitFrame();
  11636. }
  11637. this.onEndFrameObservable.notifyObservers(this);
  11638. };
  11639. /**
  11640. * resize the view according to the canvas' size.
  11641. * @example
  11642. * window.addEventListener("resize", function () {
  11643. * engine.resize();
  11644. * });
  11645. */
  11646. Engine.prototype.resize = function () {
  11647. // We're not resizing the size of the canvas while in VR mode & presenting
  11648. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11649. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11650. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11651. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11652. }
  11653. };
  11654. /**
  11655. * force a specific size of the canvas
  11656. * @param {number} width - the new canvas' width
  11657. * @param {number} height - the new canvas' height
  11658. */
  11659. Engine.prototype.setSize = function (width, height) {
  11660. if (!this._renderingCanvas) {
  11661. return;
  11662. }
  11663. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11664. return;
  11665. }
  11666. this._renderingCanvas.width = width;
  11667. this._renderingCanvas.height = height;
  11668. for (var index = 0; index < this.scenes.length; index++) {
  11669. var scene = this.scenes[index];
  11670. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11671. var cam = scene.cameras[camIndex];
  11672. cam._currentRenderId = 0;
  11673. }
  11674. }
  11675. if (this.onResizeObservable.hasObservers) {
  11676. this.onResizeObservable.notifyObservers(this);
  11677. }
  11678. };
  11679. // WebVR functions
  11680. Engine.prototype.isVRDevicePresent = function () {
  11681. return !!this._vrDisplay;
  11682. };
  11683. Engine.prototype.getVRDevice = function () {
  11684. return this._vrDisplay;
  11685. };
  11686. /**
  11687. * Initializes a webVR display and starts listening to display change events.
  11688. * The onVRDisplayChangedObservable will be notified upon these changes.
  11689. * @returns The onVRDisplayChangedObservable.
  11690. */
  11691. Engine.prototype.initWebVR = function () {
  11692. this.initWebVRAsync();
  11693. return this.onVRDisplayChangedObservable;
  11694. };
  11695. /**
  11696. * Initializes a webVR display and starts listening to display change events.
  11697. * The onVRDisplayChangedObservable will be notified upon these changes.
  11698. * @returns A promise containing a VRDisplay and if vr is supported.
  11699. */
  11700. Engine.prototype.initWebVRAsync = function () {
  11701. var _this = this;
  11702. var notifyObservers = function () {
  11703. var eventArgs = {
  11704. vrDisplay: _this._vrDisplay,
  11705. vrSupported: _this._vrSupported
  11706. };
  11707. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11708. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11709. };
  11710. if (!this._onVrDisplayConnect) {
  11711. this._onVrDisplayConnect = function (event) {
  11712. _this._vrDisplay = event.display;
  11713. notifyObservers();
  11714. };
  11715. this._onVrDisplayDisconnect = function () {
  11716. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11717. _this._vrDisplay = undefined;
  11718. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11719. notifyObservers();
  11720. };
  11721. this._onVrDisplayPresentChange = function () {
  11722. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11723. };
  11724. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11725. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11726. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11727. }
  11728. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11729. this._webVRInitPromise.then(notifyObservers);
  11730. return this._webVRInitPromise;
  11731. };
  11732. Engine.prototype.enableVR = function () {
  11733. var _this = this;
  11734. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11735. var onResolved = function () {
  11736. _this.onVRRequestPresentComplete.notifyObservers(true);
  11737. _this._onVRFullScreenTriggered();
  11738. };
  11739. var onRejected = function () {
  11740. _this.onVRRequestPresentComplete.notifyObservers(false);
  11741. };
  11742. this.onVRRequestPresentStart.notifyObservers(this);
  11743. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11744. }
  11745. };
  11746. Engine.prototype.disableVR = function () {
  11747. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11748. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11749. }
  11750. };
  11751. Engine.prototype._getVRDisplaysAsync = function () {
  11752. var _this = this;
  11753. return new Promise(function (res, rej) {
  11754. if (navigator.getVRDisplays) {
  11755. navigator.getVRDisplays().then(function (devices) {
  11756. _this._vrSupported = true;
  11757. // note that devices may actually be an empty array. This is fine;
  11758. // we expect this._vrDisplay to be undefined in this case.
  11759. _this._vrDisplay = devices[0];
  11760. res({
  11761. vrDisplay: _this._vrDisplay,
  11762. vrSupported: _this._vrSupported
  11763. });
  11764. });
  11765. }
  11766. else {
  11767. _this._vrDisplay = undefined;
  11768. _this._vrSupported = false;
  11769. res({
  11770. vrDisplay: _this._vrDisplay,
  11771. vrSupported: _this._vrSupported
  11772. });
  11773. }
  11774. });
  11775. };
  11776. /**
  11777. * Binds the frame buffer to the specified texture.
  11778. * @param texture The texture to render to or null for the default canvas
  11779. * @param faceIndex The face of the texture to render to in case of cube texture
  11780. * @param requiredWidth The width of the target to render to
  11781. * @param requiredHeight The height of the target to render to
  11782. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  11783. * @param depthStencilTexture The depth stencil texture to use to render
  11784. */
  11785. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  11786. if (this._currentRenderTarget) {
  11787. this.unBindFramebuffer(this._currentRenderTarget);
  11788. }
  11789. this._currentRenderTarget = texture;
  11790. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11791. var gl = this._gl;
  11792. if (texture.isCube) {
  11793. if (faceIndex === undefined) {
  11794. faceIndex = 0;
  11795. }
  11796. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11797. if (depthStencilTexture) {
  11798. if (depthStencilTexture._generateStencilBuffer) {
  11799. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11800. }
  11801. else {
  11802. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11803. }
  11804. }
  11805. }
  11806. if (this._cachedViewport && !forceFullscreenViewport) {
  11807. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  11808. }
  11809. else {
  11810. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  11811. }
  11812. this.wipeCaches();
  11813. };
  11814. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  11815. if (this._currentFramebuffer !== framebuffer) {
  11816. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  11817. this._currentFramebuffer = framebuffer;
  11818. }
  11819. };
  11820. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  11821. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11822. this._currentRenderTarget = null;
  11823. // If MSAA, we need to bitblt back to main texture
  11824. var gl = this._gl;
  11825. if (texture._MSAAFramebuffer) {
  11826. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  11827. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  11828. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11829. }
  11830. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11831. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11832. gl.generateMipmap(gl.TEXTURE_2D);
  11833. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11834. }
  11835. if (onBeforeUnbind) {
  11836. if (texture._MSAAFramebuffer) {
  11837. // Bind the correct framebuffer
  11838. this.bindUnboundFramebuffer(texture._framebuffer);
  11839. }
  11840. onBeforeUnbind();
  11841. }
  11842. this.bindUnboundFramebuffer(null);
  11843. };
  11844. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  11845. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11846. this._currentRenderTarget = null;
  11847. // If MSAA, we need to bitblt back to main texture
  11848. var gl = this._gl;
  11849. if (textures[0]._MSAAFramebuffer) {
  11850. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  11851. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  11852. var attachments = textures[0]._attachments;
  11853. if (!attachments) {
  11854. attachments = new Array(textures.length);
  11855. textures[0]._attachments = attachments;
  11856. }
  11857. for (var i = 0; i < textures.length; i++) {
  11858. var texture = textures[i];
  11859. for (var j = 0; j < attachments.length; j++) {
  11860. attachments[j] = gl.NONE;
  11861. }
  11862. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11863. gl.readBuffer(attachments[i]);
  11864. gl.drawBuffers(attachments);
  11865. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11866. }
  11867. for (var i = 0; i < attachments.length; i++) {
  11868. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11869. }
  11870. gl.drawBuffers(attachments);
  11871. }
  11872. for (var i = 0; i < textures.length; i++) {
  11873. var texture = textures[i];
  11874. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11875. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11876. gl.generateMipmap(gl.TEXTURE_2D);
  11877. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11878. }
  11879. }
  11880. if (onBeforeUnbind) {
  11881. if (textures[0]._MSAAFramebuffer) {
  11882. // Bind the correct framebuffer
  11883. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  11884. }
  11885. onBeforeUnbind();
  11886. }
  11887. this.bindUnboundFramebuffer(null);
  11888. };
  11889. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  11890. if (texture.generateMipMaps) {
  11891. var gl = this._gl;
  11892. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11893. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11894. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11895. }
  11896. };
  11897. Engine.prototype.flushFramebuffer = function () {
  11898. this._gl.flush();
  11899. };
  11900. Engine.prototype.restoreDefaultFramebuffer = function () {
  11901. if (this._currentRenderTarget) {
  11902. this.unBindFramebuffer(this._currentRenderTarget);
  11903. }
  11904. else {
  11905. this.bindUnboundFramebuffer(null);
  11906. }
  11907. if (this._cachedViewport) {
  11908. this.setViewport(this._cachedViewport);
  11909. }
  11910. this.wipeCaches();
  11911. };
  11912. // UBOs
  11913. Engine.prototype.createUniformBuffer = function (elements) {
  11914. var ubo = this._gl.createBuffer();
  11915. if (!ubo) {
  11916. throw new Error("Unable to create uniform buffer");
  11917. }
  11918. this.bindUniformBuffer(ubo);
  11919. if (elements instanceof Float32Array) {
  11920. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  11921. }
  11922. else {
  11923. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  11924. }
  11925. this.bindUniformBuffer(null);
  11926. ubo.references = 1;
  11927. return ubo;
  11928. };
  11929. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  11930. var ubo = this._gl.createBuffer();
  11931. if (!ubo) {
  11932. throw new Error("Unable to create dynamic uniform buffer");
  11933. }
  11934. this.bindUniformBuffer(ubo);
  11935. if (elements instanceof Float32Array) {
  11936. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  11937. }
  11938. else {
  11939. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  11940. }
  11941. this.bindUniformBuffer(null);
  11942. ubo.references = 1;
  11943. return ubo;
  11944. };
  11945. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  11946. this.bindUniformBuffer(uniformBuffer);
  11947. if (offset === undefined) {
  11948. offset = 0;
  11949. }
  11950. if (count === undefined) {
  11951. if (elements instanceof Float32Array) {
  11952. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  11953. }
  11954. else {
  11955. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  11956. }
  11957. }
  11958. else {
  11959. if (elements instanceof Float32Array) {
  11960. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  11961. }
  11962. else {
  11963. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  11964. }
  11965. }
  11966. this.bindUniformBuffer(null);
  11967. };
  11968. // VBOs
  11969. Engine.prototype._resetVertexBufferBinding = function () {
  11970. this.bindArrayBuffer(null);
  11971. this._cachedVertexBuffers = null;
  11972. };
  11973. Engine.prototype.createVertexBuffer = function (vertices) {
  11974. var vbo = this._gl.createBuffer();
  11975. if (!vbo) {
  11976. throw new Error("Unable to create vertex buffer");
  11977. }
  11978. this.bindArrayBuffer(vbo);
  11979. if (vertices instanceof Float32Array) {
  11980. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  11981. }
  11982. else {
  11983. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  11984. }
  11985. this._resetVertexBufferBinding();
  11986. vbo.references = 1;
  11987. return vbo;
  11988. };
  11989. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  11990. var vbo = this._gl.createBuffer();
  11991. if (!vbo) {
  11992. throw new Error("Unable to create dynamic vertex buffer");
  11993. }
  11994. this.bindArrayBuffer(vbo);
  11995. if (vertices instanceof Float32Array) {
  11996. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  11997. }
  11998. else {
  11999. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  12000. }
  12001. this._resetVertexBufferBinding();
  12002. vbo.references = 1;
  12003. return vbo;
  12004. };
  12005. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12006. if (offset === void 0) { offset = 0; }
  12007. // Force cache update
  12008. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12009. this.bindIndexBuffer(indexBuffer);
  12010. var arrayBuffer;
  12011. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12012. arrayBuffer = indices;
  12013. }
  12014. else {
  12015. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12016. }
  12017. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12018. this._resetIndexBufferBinding();
  12019. };
  12020. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12021. this.bindArrayBuffer(vertexBuffer);
  12022. if (offset === undefined) {
  12023. offset = 0;
  12024. }
  12025. if (count === undefined) {
  12026. if (vertices instanceof Float32Array) {
  12027. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12028. }
  12029. else {
  12030. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12031. }
  12032. }
  12033. else {
  12034. if (vertices instanceof Float32Array) {
  12035. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12036. }
  12037. else {
  12038. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12039. }
  12040. }
  12041. this._resetVertexBufferBinding();
  12042. };
  12043. Engine.prototype._resetIndexBufferBinding = function () {
  12044. this.bindIndexBuffer(null);
  12045. this._cachedIndexBuffer = null;
  12046. };
  12047. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12048. var vbo = this._gl.createBuffer();
  12049. if (!vbo) {
  12050. throw new Error("Unable to create index buffer");
  12051. }
  12052. this.bindIndexBuffer(vbo);
  12053. // Check for 32 bits indices
  12054. var arrayBuffer;
  12055. var need32Bits = false;
  12056. if (indices instanceof Uint16Array) {
  12057. arrayBuffer = indices;
  12058. }
  12059. else {
  12060. //check 32 bit support
  12061. if (this._caps.uintIndices) {
  12062. if (indices instanceof Uint32Array) {
  12063. arrayBuffer = indices;
  12064. need32Bits = true;
  12065. }
  12066. else {
  12067. //number[] or Int32Array, check if 32 bit is necessary
  12068. for (var index = 0; index < indices.length; index++) {
  12069. if (indices[index] > 65535) {
  12070. need32Bits = true;
  12071. break;
  12072. }
  12073. }
  12074. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12075. }
  12076. }
  12077. else {
  12078. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12079. arrayBuffer = new Uint16Array(indices);
  12080. }
  12081. }
  12082. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12083. this._resetIndexBufferBinding();
  12084. vbo.references = 1;
  12085. vbo.is32Bits = need32Bits;
  12086. return vbo;
  12087. };
  12088. Engine.prototype.bindArrayBuffer = function (buffer) {
  12089. if (!this._vaoRecordInProgress) {
  12090. this._unbindVertexArrayObject();
  12091. }
  12092. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12093. };
  12094. Engine.prototype.bindUniformBuffer = function (buffer) {
  12095. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12096. };
  12097. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12098. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12099. };
  12100. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12101. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12102. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12103. };
  12104. ;
  12105. Engine.prototype.bindIndexBuffer = function (buffer) {
  12106. if (!this._vaoRecordInProgress) {
  12107. this._unbindVertexArrayObject();
  12108. }
  12109. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12110. };
  12111. Engine.prototype.bindBuffer = function (buffer, target) {
  12112. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12113. this._gl.bindBuffer(target, buffer);
  12114. this._currentBoundBuffer[target] = buffer;
  12115. }
  12116. };
  12117. Engine.prototype.updateArrayBuffer = function (data) {
  12118. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12119. };
  12120. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12121. var pointer = this._currentBufferPointers[indx];
  12122. var changed = false;
  12123. if (!pointer.active) {
  12124. changed = true;
  12125. pointer.active = true;
  12126. pointer.index = indx;
  12127. pointer.size = size;
  12128. pointer.type = type;
  12129. pointer.normalized = normalized;
  12130. pointer.stride = stride;
  12131. pointer.offset = offset;
  12132. pointer.buffer = buffer;
  12133. }
  12134. else {
  12135. if (pointer.buffer !== buffer) {
  12136. pointer.buffer = buffer;
  12137. changed = true;
  12138. }
  12139. if (pointer.size !== size) {
  12140. pointer.size = size;
  12141. changed = true;
  12142. }
  12143. if (pointer.type !== type) {
  12144. pointer.type = type;
  12145. changed = true;
  12146. }
  12147. if (pointer.normalized !== normalized) {
  12148. pointer.normalized = normalized;
  12149. changed = true;
  12150. }
  12151. if (pointer.stride !== stride) {
  12152. pointer.stride = stride;
  12153. changed = true;
  12154. }
  12155. if (pointer.offset !== offset) {
  12156. pointer.offset = offset;
  12157. changed = true;
  12158. }
  12159. }
  12160. if (changed || this._vaoRecordInProgress) {
  12161. this.bindArrayBuffer(buffer);
  12162. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12163. }
  12164. };
  12165. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12166. if (indexBuffer == null) {
  12167. return;
  12168. }
  12169. if (this._cachedIndexBuffer !== indexBuffer) {
  12170. this._cachedIndexBuffer = indexBuffer;
  12171. this.bindIndexBuffer(indexBuffer);
  12172. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12173. }
  12174. };
  12175. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12176. var attributes = effect.getAttributesNames();
  12177. if (!this._vaoRecordInProgress) {
  12178. this._unbindVertexArrayObject();
  12179. }
  12180. this.unbindAllAttributes();
  12181. for (var index = 0; index < attributes.length; index++) {
  12182. var order = effect.getAttributeLocation(index);
  12183. if (order >= 0) {
  12184. var vertexBuffer = vertexBuffers[attributes[index]];
  12185. if (!vertexBuffer) {
  12186. continue;
  12187. }
  12188. this._gl.enableVertexAttribArray(order);
  12189. if (!this._vaoRecordInProgress) {
  12190. this._vertexAttribArraysEnabled[order] = true;
  12191. }
  12192. var buffer = vertexBuffer.getBuffer();
  12193. if (buffer) {
  12194. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12195. if (vertexBuffer.getIsInstanced()) {
  12196. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12197. if (!this._vaoRecordInProgress) {
  12198. this._currentInstanceLocations.push(order);
  12199. this._currentInstanceBuffers.push(buffer);
  12200. }
  12201. }
  12202. }
  12203. }
  12204. }
  12205. };
  12206. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12207. var vao = this._gl.createVertexArray();
  12208. this._vaoRecordInProgress = true;
  12209. this._gl.bindVertexArray(vao);
  12210. this._mustWipeVertexAttributes = true;
  12211. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12212. this.bindIndexBuffer(indexBuffer);
  12213. this._vaoRecordInProgress = false;
  12214. this._gl.bindVertexArray(null);
  12215. return vao;
  12216. };
  12217. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12218. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12219. this._cachedVertexArrayObject = vertexArrayObject;
  12220. this._gl.bindVertexArray(vertexArrayObject);
  12221. this._cachedVertexBuffers = null;
  12222. this._cachedIndexBuffer = null;
  12223. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12224. this._mustWipeVertexAttributes = true;
  12225. }
  12226. };
  12227. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12228. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12229. this._cachedVertexBuffers = vertexBuffer;
  12230. this._cachedEffectForVertexBuffers = effect;
  12231. var attributesCount = effect.getAttributesCount();
  12232. this._unbindVertexArrayObject();
  12233. this.unbindAllAttributes();
  12234. var offset = 0;
  12235. for (var index = 0; index < attributesCount; index++) {
  12236. if (index < vertexDeclaration.length) {
  12237. var order = effect.getAttributeLocation(index);
  12238. if (order >= 0) {
  12239. this._gl.enableVertexAttribArray(order);
  12240. this._vertexAttribArraysEnabled[order] = true;
  12241. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12242. }
  12243. offset += vertexDeclaration[index] * 4;
  12244. }
  12245. }
  12246. }
  12247. this._bindIndexBufferWithCache(indexBuffer);
  12248. };
  12249. Engine.prototype._unbindVertexArrayObject = function () {
  12250. if (!this._cachedVertexArrayObject) {
  12251. return;
  12252. }
  12253. this._cachedVertexArrayObject = null;
  12254. this._gl.bindVertexArray(null);
  12255. };
  12256. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12257. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12258. this._cachedVertexBuffers = vertexBuffers;
  12259. this._cachedEffectForVertexBuffers = effect;
  12260. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12261. }
  12262. this._bindIndexBufferWithCache(indexBuffer);
  12263. };
  12264. Engine.prototype.unbindInstanceAttributes = function () {
  12265. var boundBuffer;
  12266. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12267. var instancesBuffer = this._currentInstanceBuffers[i];
  12268. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12269. boundBuffer = instancesBuffer;
  12270. this.bindArrayBuffer(instancesBuffer);
  12271. }
  12272. var offsetLocation = this._currentInstanceLocations[i];
  12273. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12274. }
  12275. this._currentInstanceBuffers.length = 0;
  12276. this._currentInstanceLocations.length = 0;
  12277. };
  12278. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12279. this._gl.deleteVertexArray(vao);
  12280. };
  12281. Engine.prototype._releaseBuffer = function (buffer) {
  12282. buffer.references--;
  12283. if (buffer.references === 0) {
  12284. this._gl.deleteBuffer(buffer);
  12285. return true;
  12286. }
  12287. return false;
  12288. };
  12289. Engine.prototype.createInstancesBuffer = function (capacity) {
  12290. var buffer = this._gl.createBuffer();
  12291. if (!buffer) {
  12292. throw new Error("Unable to create instance buffer");
  12293. }
  12294. buffer.capacity = capacity;
  12295. this.bindArrayBuffer(buffer);
  12296. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12297. return buffer;
  12298. };
  12299. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12300. this._gl.deleteBuffer(buffer);
  12301. };
  12302. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12303. this.bindArrayBuffer(instancesBuffer);
  12304. if (data) {
  12305. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12306. }
  12307. if (offsetLocations[0].index !== undefined) {
  12308. var stride = 0;
  12309. for (var i = 0; i < offsetLocations.length; i++) {
  12310. var ai = offsetLocations[i];
  12311. stride += ai.attributeSize * 4;
  12312. }
  12313. for (var i = 0; i < offsetLocations.length; i++) {
  12314. var ai = offsetLocations[i];
  12315. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12316. this._gl.enableVertexAttribArray(ai.index);
  12317. this._vertexAttribArraysEnabled[ai.index] = true;
  12318. }
  12319. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12320. this._gl.vertexAttribDivisor(ai.index, 1);
  12321. this._currentInstanceLocations.push(ai.index);
  12322. this._currentInstanceBuffers.push(instancesBuffer);
  12323. }
  12324. }
  12325. else {
  12326. for (var index = 0; index < 4; index++) {
  12327. var offsetLocation = offsetLocations[index];
  12328. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12329. this._gl.enableVertexAttribArray(offsetLocation);
  12330. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12331. }
  12332. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12333. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12334. this._currentInstanceLocations.push(offsetLocation);
  12335. this._currentInstanceBuffers.push(instancesBuffer);
  12336. }
  12337. }
  12338. };
  12339. Engine.prototype.applyStates = function () {
  12340. this._depthCullingState.apply(this._gl);
  12341. this._stencilState.apply(this._gl);
  12342. this._alphaState.apply(this._gl);
  12343. };
  12344. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12345. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12346. };
  12347. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12348. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12349. };
  12350. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12351. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12352. };
  12353. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12354. // Apply states
  12355. this.applyStates();
  12356. this._drawCalls.addCount(1, false);
  12357. // Render
  12358. var drawMode = this.DrawMode(fillMode);
  12359. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12360. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12361. if (instancesCount) {
  12362. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12363. }
  12364. else {
  12365. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12366. }
  12367. };
  12368. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12369. // Apply states
  12370. this.applyStates();
  12371. this._drawCalls.addCount(1, false);
  12372. var drawMode = this.DrawMode(fillMode);
  12373. if (instancesCount) {
  12374. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12375. }
  12376. else {
  12377. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12378. }
  12379. };
  12380. Engine.prototype.DrawMode = function (fillMode) {
  12381. switch (fillMode) {
  12382. // Triangle views
  12383. case BABYLON.Material.TriangleFillMode:
  12384. return this._gl.TRIANGLES;
  12385. case BABYLON.Material.PointFillMode:
  12386. return this._gl.POINTS;
  12387. case BABYLON.Material.WireFrameFillMode:
  12388. return this._gl.LINES;
  12389. // Draw modes
  12390. case BABYLON.Material.PointListDrawMode:
  12391. return this._gl.POINTS;
  12392. case BABYLON.Material.LineListDrawMode:
  12393. return this._gl.LINES;
  12394. case BABYLON.Material.LineLoopDrawMode:
  12395. return this._gl.LINE_LOOP;
  12396. case BABYLON.Material.LineStripDrawMode:
  12397. return this._gl.LINE_STRIP;
  12398. case BABYLON.Material.TriangleStripDrawMode:
  12399. return this._gl.TRIANGLE_STRIP;
  12400. case BABYLON.Material.TriangleFanDrawMode:
  12401. return this._gl.TRIANGLE_FAN;
  12402. default:
  12403. return this._gl.TRIANGLES;
  12404. }
  12405. };
  12406. // Shaders
  12407. Engine.prototype._releaseEffect = function (effect) {
  12408. if (this._compiledEffects[effect._key]) {
  12409. delete this._compiledEffects[effect._key];
  12410. this._deleteProgram(effect.getProgram());
  12411. }
  12412. };
  12413. Engine.prototype._deleteProgram = function (program) {
  12414. if (program) {
  12415. program.__SPECTOR_rebuildProgram = null;
  12416. if (program.transformFeedback) {
  12417. this.deleteTransformFeedback(program.transformFeedback);
  12418. program.transformFeedback = null;
  12419. }
  12420. this._gl.deleteProgram(program);
  12421. }
  12422. };
  12423. /**
  12424. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12425. * @param samplers An array of string used to represent textures
  12426. */
  12427. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12428. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12429. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12430. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12431. if (this._compiledEffects[name]) {
  12432. var compiledEffect = this._compiledEffects[name];
  12433. if (onCompiled && compiledEffect.isReady()) {
  12434. onCompiled(compiledEffect);
  12435. }
  12436. return compiledEffect;
  12437. }
  12438. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12439. effect._key = name;
  12440. this._compiledEffects[name] = effect;
  12441. return effect;
  12442. };
  12443. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12444. if (uniformsNames === void 0) { uniformsNames = []; }
  12445. if (samplers === void 0) { samplers = []; }
  12446. if (defines === void 0) { defines = ""; }
  12447. return this.createEffect({
  12448. vertex: "particles",
  12449. fragmentElement: fragmentName
  12450. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12451. };
  12452. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12453. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12454. context = context || this._gl;
  12455. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12456. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12457. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12458. };
  12459. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12460. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12461. context = context || this._gl;
  12462. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12463. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  12464. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12465. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12466. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12467. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12468. return program;
  12469. };
  12470. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12471. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12472. var shaderProgram = context.createProgram();
  12473. if (!shaderProgram) {
  12474. throw new Error("Unable to create program");
  12475. }
  12476. context.attachShader(shaderProgram, vertexShader);
  12477. context.attachShader(shaderProgram, fragmentShader);
  12478. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12479. var transformFeedback = this.createTransformFeedback();
  12480. this.bindTransformFeedback(transformFeedback);
  12481. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12482. shaderProgram.transformFeedback = transformFeedback;
  12483. }
  12484. context.linkProgram(shaderProgram);
  12485. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12486. this.bindTransformFeedback(null);
  12487. }
  12488. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12489. if (!linked) {
  12490. context.validateProgram(shaderProgram);
  12491. var error = context.getProgramInfoLog(shaderProgram);
  12492. if (error) {
  12493. throw new Error(error);
  12494. }
  12495. }
  12496. context.deleteShader(vertexShader);
  12497. context.deleteShader(fragmentShader);
  12498. return shaderProgram;
  12499. };
  12500. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12501. var results = new Array();
  12502. for (var index = 0; index < uniformsNames.length; index++) {
  12503. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12504. }
  12505. return results;
  12506. };
  12507. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12508. var results = [];
  12509. for (var index = 0; index < attributesNames.length; index++) {
  12510. try {
  12511. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12512. }
  12513. catch (e) {
  12514. results.push(-1);
  12515. }
  12516. }
  12517. return results;
  12518. };
  12519. Engine.prototype.enableEffect = function (effect) {
  12520. if (!effect) {
  12521. return;
  12522. }
  12523. // Use program
  12524. this.bindSamplers(effect);
  12525. this._currentEffect = effect;
  12526. if (effect.onBind) {
  12527. effect.onBind(effect);
  12528. }
  12529. effect.onBindObservable.notifyObservers(effect);
  12530. };
  12531. Engine.prototype.setIntArray = function (uniform, array) {
  12532. if (!uniform)
  12533. return;
  12534. this._gl.uniform1iv(uniform, array);
  12535. };
  12536. Engine.prototype.setIntArray2 = function (uniform, array) {
  12537. if (!uniform || array.length % 2 !== 0)
  12538. return;
  12539. this._gl.uniform2iv(uniform, array);
  12540. };
  12541. Engine.prototype.setIntArray3 = function (uniform, array) {
  12542. if (!uniform || array.length % 3 !== 0)
  12543. return;
  12544. this._gl.uniform3iv(uniform, array);
  12545. };
  12546. Engine.prototype.setIntArray4 = function (uniform, array) {
  12547. if (!uniform || array.length % 4 !== 0)
  12548. return;
  12549. this._gl.uniform4iv(uniform, array);
  12550. };
  12551. Engine.prototype.setFloatArray = function (uniform, array) {
  12552. if (!uniform)
  12553. return;
  12554. this._gl.uniform1fv(uniform, array);
  12555. };
  12556. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12557. if (!uniform || array.length % 2 !== 0)
  12558. return;
  12559. this._gl.uniform2fv(uniform, array);
  12560. };
  12561. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12562. if (!uniform || array.length % 3 !== 0)
  12563. return;
  12564. this._gl.uniform3fv(uniform, array);
  12565. };
  12566. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12567. if (!uniform || array.length % 4 !== 0)
  12568. return;
  12569. this._gl.uniform4fv(uniform, array);
  12570. };
  12571. Engine.prototype.setArray = function (uniform, array) {
  12572. if (!uniform)
  12573. return;
  12574. this._gl.uniform1fv(uniform, array);
  12575. };
  12576. Engine.prototype.setArray2 = function (uniform, array) {
  12577. if (!uniform || array.length % 2 !== 0)
  12578. return;
  12579. this._gl.uniform2fv(uniform, array);
  12580. };
  12581. Engine.prototype.setArray3 = function (uniform, array) {
  12582. if (!uniform || array.length % 3 !== 0)
  12583. return;
  12584. this._gl.uniform3fv(uniform, array);
  12585. };
  12586. Engine.prototype.setArray4 = function (uniform, array) {
  12587. if (!uniform || array.length % 4 !== 0)
  12588. return;
  12589. this._gl.uniform4fv(uniform, array);
  12590. };
  12591. Engine.prototype.setMatrices = function (uniform, matrices) {
  12592. if (!uniform)
  12593. return;
  12594. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12595. };
  12596. Engine.prototype.setMatrix = function (uniform, matrix) {
  12597. if (!uniform)
  12598. return;
  12599. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12600. };
  12601. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12602. if (!uniform)
  12603. return;
  12604. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12605. };
  12606. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12607. if (!uniform)
  12608. return;
  12609. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12610. };
  12611. Engine.prototype.setInt = function (uniform, value) {
  12612. if (!uniform)
  12613. return;
  12614. this._gl.uniform1i(uniform, value);
  12615. };
  12616. Engine.prototype.setFloat = function (uniform, value) {
  12617. if (!uniform)
  12618. return;
  12619. this._gl.uniform1f(uniform, value);
  12620. };
  12621. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12622. if (!uniform)
  12623. return;
  12624. this._gl.uniform2f(uniform, x, y);
  12625. };
  12626. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12627. if (!uniform)
  12628. return;
  12629. this._gl.uniform3f(uniform, x, y, z);
  12630. };
  12631. Engine.prototype.setBool = function (uniform, bool) {
  12632. if (!uniform)
  12633. return;
  12634. this._gl.uniform1i(uniform, bool);
  12635. };
  12636. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12637. if (!uniform)
  12638. return;
  12639. this._gl.uniform4f(uniform, x, y, z, w);
  12640. };
  12641. Engine.prototype.setColor3 = function (uniform, color3) {
  12642. if (!uniform)
  12643. return;
  12644. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12645. };
  12646. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12647. if (!uniform)
  12648. return;
  12649. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12650. };
  12651. /**
  12652. * Sets a Color4 on a uniform variable
  12653. * @param uniform defines the uniform location
  12654. * @param color4 defines the value to be set
  12655. */
  12656. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12657. if (!uniform)
  12658. return;
  12659. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12660. };
  12661. // States
  12662. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12663. if (zOffset === void 0) { zOffset = 0; }
  12664. if (reverseSide === void 0) { reverseSide = false; }
  12665. // Culling
  12666. if (this._depthCullingState.cull !== culling || force) {
  12667. this._depthCullingState.cull = culling;
  12668. }
  12669. // Cull face
  12670. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12671. if (this._depthCullingState.cullFace !== cullFace || force) {
  12672. this._depthCullingState.cullFace = cullFace;
  12673. }
  12674. // Z offset
  12675. this.setZOffset(zOffset);
  12676. // Front face
  12677. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12678. if (this._depthCullingState.frontFace !== frontFace || force) {
  12679. this._depthCullingState.frontFace = frontFace;
  12680. }
  12681. };
  12682. Engine.prototype.setZOffset = function (value) {
  12683. this._depthCullingState.zOffset = value;
  12684. };
  12685. Engine.prototype.getZOffset = function () {
  12686. return this._depthCullingState.zOffset;
  12687. };
  12688. Engine.prototype.setDepthBuffer = function (enable) {
  12689. this._depthCullingState.depthTest = enable;
  12690. };
  12691. Engine.prototype.getDepthWrite = function () {
  12692. return this._depthCullingState.depthMask;
  12693. };
  12694. Engine.prototype.setDepthWrite = function (enable) {
  12695. this._depthCullingState.depthMask = enable;
  12696. };
  12697. Engine.prototype.setColorWrite = function (enable) {
  12698. this._gl.colorMask(enable, enable, enable, enable);
  12699. this._colorWrite = enable;
  12700. };
  12701. Engine.prototype.getColorWrite = function () {
  12702. return this._colorWrite;
  12703. };
  12704. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12705. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12706. };
  12707. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12708. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12709. if (this._alphaMode === mode) {
  12710. return;
  12711. }
  12712. switch (mode) {
  12713. case Engine.ALPHA_DISABLE:
  12714. this._alphaState.alphaBlend = false;
  12715. break;
  12716. case Engine.ALPHA_PREMULTIPLIED:
  12717. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12718. this._alphaState.alphaBlend = true;
  12719. break;
  12720. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12721. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12722. this._alphaState.alphaBlend = true;
  12723. break;
  12724. case Engine.ALPHA_COMBINE:
  12725. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12726. this._alphaState.alphaBlend = true;
  12727. break;
  12728. case Engine.ALPHA_ONEONE:
  12729. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12730. this._alphaState.alphaBlend = true;
  12731. break;
  12732. case Engine.ALPHA_ADD:
  12733. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12734. this._alphaState.alphaBlend = true;
  12735. break;
  12736. case Engine.ALPHA_SUBTRACT:
  12737. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12738. this._alphaState.alphaBlend = true;
  12739. break;
  12740. case Engine.ALPHA_MULTIPLY:
  12741. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12742. this._alphaState.alphaBlend = true;
  12743. break;
  12744. case Engine.ALPHA_MAXIMIZED:
  12745. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12746. this._alphaState.alphaBlend = true;
  12747. break;
  12748. case Engine.ALPHA_INTERPOLATE:
  12749. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12750. this._alphaState.alphaBlend = true;
  12751. break;
  12752. case Engine.ALPHA_SCREENMODE:
  12753. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12754. this._alphaState.alphaBlend = true;
  12755. break;
  12756. }
  12757. if (!noDepthWriteChange) {
  12758. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12759. }
  12760. this._alphaMode = mode;
  12761. };
  12762. Engine.prototype.getAlphaMode = function () {
  12763. return this._alphaMode;
  12764. };
  12765. // Textures
  12766. Engine.prototype.wipeCaches = function (bruteForce) {
  12767. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12768. return;
  12769. }
  12770. this._currentEffect = null;
  12771. // 6/8/2017: deltakosh: Should not be required anymore.
  12772. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12773. if (bruteForce) {
  12774. this.resetTextureCache();
  12775. this._currentProgram = null;
  12776. this._stencilState.reset();
  12777. this._depthCullingState.reset();
  12778. this.setDepthFunctionToLessOrEqual();
  12779. this._alphaState.reset();
  12780. }
  12781. this._resetVertexBufferBinding();
  12782. this._cachedIndexBuffer = null;
  12783. this._cachedEffectForVertexBuffers = null;
  12784. this._unbindVertexArrayObject();
  12785. this.bindIndexBuffer(null);
  12786. };
  12787. /**
  12788. * Set the compressed texture format to use, based on the formats you have, and the formats
  12789. * supported by the hardware / browser.
  12790. *
  12791. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12792. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12793. * to API arguments needed to compressed textures. This puts the burden on the container
  12794. * generator to house the arcane code for determining these for current & future formats.
  12795. *
  12796. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12797. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12798. *
  12799. * Note: The result of this call is not taken into account when a texture is base64.
  12800. *
  12801. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  12802. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  12803. *
  12804. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  12805. * @returns The extension selected.
  12806. */
  12807. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  12808. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  12809. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  12810. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  12811. return this._textureFormatInUse = this._texturesSupported[i];
  12812. }
  12813. }
  12814. }
  12815. // actively set format to nothing, to allow this to be called more than once
  12816. // and possibly fail the 2nd time
  12817. this._textureFormatInUse = null;
  12818. return null;
  12819. };
  12820. Engine.prototype._createTexture = function () {
  12821. var texture = this._gl.createTexture();
  12822. if (!texture) {
  12823. throw new Error("Unable to create texture");
  12824. }
  12825. return texture;
  12826. };
  12827. /**
  12828. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  12829. * @param {string} urlArg- This contains one of the following:
  12830. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  12831. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  12832. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  12833. *
  12834. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  12835. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  12836. * @param {Scene} scene- Needed for loading to the correct scene.
  12837. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  12838. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  12839. * @param {callback} onError- Optional callback to be called upon failure.
  12840. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  12841. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  12842. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  12843. *
  12844. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  12845. */
  12846. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  12847. var _this = this;
  12848. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12849. if (onLoad === void 0) { onLoad = null; }
  12850. if (onError === void 0) { onError = null; }
  12851. if (buffer === void 0) { buffer = null; }
  12852. if (fallBack === void 0) { fallBack = null; }
  12853. if (format === void 0) { format = null; }
  12854. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  12855. var fromData = url.substr(0, 5) === "data:";
  12856. var fromBlob = url.substr(0, 5) === "blob:";
  12857. var isBase64 = fromData && url.indexOf("base64") !== -1;
  12858. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  12859. // establish the file extension, if possible
  12860. var lastDot = url.lastIndexOf('.');
  12861. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  12862. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  12863. var isTGA = (extension.indexOf(".tga") === 0);
  12864. // determine if a ktx file should be substituted
  12865. var isKTX = false;
  12866. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  12867. url = url.substring(0, lastDot) + this._textureFormatInUse;
  12868. isKTX = true;
  12869. }
  12870. if (scene) {
  12871. scene._addPendingData(texture);
  12872. }
  12873. texture.url = url;
  12874. texture.generateMipMaps = !noMipmap;
  12875. texture.samplingMode = samplingMode;
  12876. texture.invertY = invertY;
  12877. if (!this._doNotHandleContextLost) {
  12878. // Keep a link to the buffer only if we plan to handle context lost
  12879. texture._buffer = buffer;
  12880. }
  12881. var onLoadObserver = null;
  12882. if (onLoad && !fallBack) {
  12883. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  12884. }
  12885. if (!fallBack)
  12886. this._internalTexturesCache.push(texture);
  12887. var onerror = function (message, exception) {
  12888. if (scene) {
  12889. scene._removePendingData(texture);
  12890. }
  12891. if (onLoadObserver) {
  12892. texture.onLoadedObservable.remove(onLoadObserver);
  12893. }
  12894. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  12895. if (isKTX) {
  12896. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12897. }
  12898. else if (BABYLON.Tools.UseFallbackTexture) {
  12899. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12900. }
  12901. if (onError) {
  12902. onError(message || "Unknown error", exception);
  12903. }
  12904. };
  12905. var callback = null;
  12906. // processing for non-image formats
  12907. if (isKTX || isTGA || isDDS) {
  12908. if (isKTX) {
  12909. callback = function (data) {
  12910. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  12911. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  12912. ktx.uploadLevels(_this._gl, !noMipmap);
  12913. return false;
  12914. }, samplingMode);
  12915. };
  12916. }
  12917. else if (isTGA) {
  12918. callback = function (arrayBuffer) {
  12919. var data = new Uint8Array(arrayBuffer);
  12920. var header = BABYLON.TGATools.GetTGAHeader(data);
  12921. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  12922. BABYLON.TGATools.UploadContent(_this._gl, data);
  12923. return false;
  12924. }, samplingMode);
  12925. };
  12926. }
  12927. else if (isDDS) {
  12928. callback = function (data) {
  12929. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12930. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  12931. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  12932. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  12933. return false;
  12934. }, samplingMode);
  12935. };
  12936. }
  12937. if (!buffer) {
  12938. this._loadFile(url, function (data) {
  12939. if (callback) {
  12940. callback(data);
  12941. }
  12942. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  12943. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  12944. });
  12945. }
  12946. else {
  12947. if (callback) {
  12948. callback(buffer);
  12949. }
  12950. }
  12951. // image format processing
  12952. }
  12953. else {
  12954. var onload = function (img) {
  12955. if (fromBlob && !_this._doNotHandleContextLost) {
  12956. // We need to store the image if we need to rebuild the texture
  12957. // in case of a webgl context lost
  12958. texture._buffer = img;
  12959. }
  12960. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  12961. var gl = _this._gl;
  12962. var isPot = (img.width === potWidth && img.height === potHeight);
  12963. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  12964. if (isPot) {
  12965. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12966. return false;
  12967. }
  12968. // Using shaders to rescale because canvas.drawImage is lossy
  12969. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12970. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  12971. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12972. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12973. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12974. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12975. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12976. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  12977. _this._releaseTexture(source);
  12978. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12979. continuationCallback();
  12980. });
  12981. return true;
  12982. }, samplingMode);
  12983. };
  12984. if (!fromData || isBase64)
  12985. if (buffer instanceof HTMLImageElement) {
  12986. onload(buffer);
  12987. }
  12988. else {
  12989. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  12990. }
  12991. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  12992. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  12993. else
  12994. onload(buffer);
  12995. }
  12996. return texture;
  12997. };
  12998. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  12999. var _this = this;
  13000. var rtt = this.createRenderTargetTexture({
  13001. width: destination.width,
  13002. height: destination.height,
  13003. }, {
  13004. generateMipMaps: false,
  13005. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13006. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13007. generateDepthBuffer: false,
  13008. generateStencilBuffer: false
  13009. });
  13010. if (!this._rescalePostProcess) {
  13011. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13012. }
  13013. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13014. _this._rescalePostProcess.onApply = function (effect) {
  13015. effect._bindTexture("textureSampler", source);
  13016. };
  13017. var hostingScene = scene;
  13018. if (!hostingScene) {
  13019. hostingScene = _this.scenes[_this.scenes.length - 1];
  13020. }
  13021. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13022. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13023. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13024. _this.unBindFramebuffer(rtt);
  13025. _this._releaseTexture(rtt);
  13026. if (onComplete) {
  13027. onComplete();
  13028. }
  13029. });
  13030. };
  13031. Engine.prototype._getInternalFormat = function (format) {
  13032. var internalFormat = this._gl.RGBA;
  13033. switch (format) {
  13034. case Engine.TEXTUREFORMAT_ALPHA:
  13035. internalFormat = this._gl.ALPHA;
  13036. break;
  13037. case Engine.TEXTUREFORMAT_LUMINANCE:
  13038. internalFormat = this._gl.LUMINANCE;
  13039. break;
  13040. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  13041. internalFormat = this._gl.LUMINANCE_ALPHA;
  13042. break;
  13043. case Engine.TEXTUREFORMAT_RGB:
  13044. case Engine.TEXTUREFORMAT_RGB32F:
  13045. internalFormat = this._gl.RGB;
  13046. break;
  13047. case Engine.TEXTUREFORMAT_RGBA:
  13048. case Engine.TEXTUREFORMAT_RGBA32F:
  13049. internalFormat = this._gl.RGBA;
  13050. break;
  13051. case Engine.TEXTUREFORMAT_R32F:
  13052. internalFormat = this._gl.RED;
  13053. break;
  13054. case Engine.TEXTUREFORMAT_RG32F:
  13055. internalFormat = this._gl.RG;
  13056. break;
  13057. }
  13058. return internalFormat;
  13059. };
  13060. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13061. if (compression === void 0) { compression = null; }
  13062. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13063. if (!texture) {
  13064. return;
  13065. }
  13066. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13067. var internalFormat = this._getInternalFormat(format);
  13068. var textureType = this._getWebGLTextureType(type);
  13069. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13070. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13071. if (!this._doNotHandleContextLost) {
  13072. texture._bufferView = data;
  13073. texture.format = format;
  13074. texture.type = type;
  13075. texture.invertY = invertY;
  13076. texture._compression = compression;
  13077. }
  13078. if (texture.width % 4 !== 0) {
  13079. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13080. }
  13081. if (compression && data) {
  13082. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13083. }
  13084. else {
  13085. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13086. }
  13087. if (texture.generateMipMaps) {
  13088. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13089. }
  13090. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13091. // this.resetTextureCache();
  13092. texture.isReady = true;
  13093. };
  13094. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13095. if (compression === void 0) { compression = null; }
  13096. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13097. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13098. texture.baseWidth = width;
  13099. texture.baseHeight = height;
  13100. texture.width = width;
  13101. texture.height = height;
  13102. texture.format = format;
  13103. texture.generateMipMaps = generateMipMaps;
  13104. texture.samplingMode = samplingMode;
  13105. texture.invertY = invertY;
  13106. texture._compression = compression;
  13107. texture.type = type;
  13108. if (!this._doNotHandleContextLost) {
  13109. texture._bufferView = data;
  13110. }
  13111. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13112. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13113. // Filters
  13114. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13115. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13116. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13117. if (generateMipMaps) {
  13118. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13119. }
  13120. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13121. this._internalTexturesCache.push(texture);
  13122. return texture;
  13123. };
  13124. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13125. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13126. texture.baseWidth = width;
  13127. texture.baseHeight = height;
  13128. if (generateMipMaps) {
  13129. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13130. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13131. }
  13132. // this.resetTextureCache();
  13133. texture.width = width;
  13134. texture.height = height;
  13135. texture.isReady = false;
  13136. texture.generateMipMaps = generateMipMaps;
  13137. texture.samplingMode = samplingMode;
  13138. this.updateTextureSamplingMode(samplingMode, texture);
  13139. this._internalTexturesCache.push(texture);
  13140. return texture;
  13141. };
  13142. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13143. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13144. if (texture.isCube) {
  13145. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13146. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13147. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13148. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13149. }
  13150. else if (texture.is3D) {
  13151. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13152. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13153. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13154. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13155. }
  13156. else {
  13157. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13158. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13159. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13160. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13161. }
  13162. texture.samplingMode = samplingMode;
  13163. };
  13164. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13165. if (premulAlpha === void 0) { premulAlpha = false; }
  13166. if (!texture) {
  13167. return;
  13168. }
  13169. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13170. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13171. if (premulAlpha) {
  13172. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13173. }
  13174. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13175. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13176. if (texture.generateMipMaps) {
  13177. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13178. }
  13179. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13180. if (premulAlpha) {
  13181. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13182. }
  13183. texture.isReady = true;
  13184. };
  13185. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13186. if (!texture || texture._isDisabled) {
  13187. return;
  13188. }
  13189. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13190. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13191. try {
  13192. // Testing video texture support
  13193. if (this._videoTextureSupported === undefined) {
  13194. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13195. if (this._gl.getError() !== 0) {
  13196. this._videoTextureSupported = false;
  13197. }
  13198. else {
  13199. this._videoTextureSupported = true;
  13200. }
  13201. }
  13202. // Copy video through the current working canvas if video texture is not supported
  13203. if (!this._videoTextureSupported) {
  13204. if (!texture._workingCanvas) {
  13205. texture._workingCanvas = document.createElement("canvas");
  13206. var context = texture._workingCanvas.getContext("2d");
  13207. if (!context) {
  13208. throw new Error("Unable to get 2d context");
  13209. }
  13210. texture._workingContext = context;
  13211. texture._workingCanvas.width = texture.width;
  13212. texture._workingCanvas.height = texture.height;
  13213. }
  13214. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13215. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13216. }
  13217. else {
  13218. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13219. }
  13220. if (texture.generateMipMaps) {
  13221. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13222. }
  13223. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13224. // this.resetTextureCache();
  13225. texture.isReady = true;
  13226. }
  13227. catch (ex) {
  13228. // Something unexpected
  13229. // Let's disable the texture
  13230. texture._isDisabled = true;
  13231. }
  13232. };
  13233. /**
  13234. * Updates a depth texture Comparison Mode and Function.
  13235. * If the comparison Function is equal to 0, the mode will be set to none.
  13236. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13237. * @param texture The texture to set the comparison function for
  13238. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13239. */
  13240. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13241. if (this.webGLVersion === 1) {
  13242. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13243. return;
  13244. }
  13245. var gl = this._gl;
  13246. if (texture.isCube) {
  13247. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13248. if (comparisonFunction === 0) {
  13249. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13250. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13251. }
  13252. else {
  13253. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13254. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13255. }
  13256. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13257. }
  13258. else {
  13259. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13260. if (comparisonFunction === 0) {
  13261. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13262. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13263. }
  13264. else {
  13265. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13266. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13267. }
  13268. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13269. }
  13270. texture._comparisonFunction = comparisonFunction;
  13271. };
  13272. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13273. var width = size.width || size;
  13274. var height = size.height || size;
  13275. internalTexture.baseWidth = width;
  13276. internalTexture.baseHeight = height;
  13277. internalTexture.width = width;
  13278. internalTexture.height = height;
  13279. internalTexture.isReady = true;
  13280. internalTexture.samples = 1;
  13281. internalTexture.generateMipMaps = false;
  13282. internalTexture._generateDepthBuffer = true;
  13283. internalTexture._generateStencilBuffer = generateStencil;
  13284. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.NEAREST_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  13285. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13286. internalTexture._comparisonFunction = comparisonFunction;
  13287. var gl = this._gl;
  13288. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13289. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13290. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13291. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13292. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13293. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13294. if (comparisonFunction === 0) {
  13295. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13296. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13297. }
  13298. else {
  13299. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13300. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13301. }
  13302. };
  13303. /**
  13304. * Creates a depth stencil texture.
  13305. * This is only available in WebGL 2 or with the depth texture extension available.
  13306. * @param size The size of face edge in the texture.
  13307. * @param options The options defining the texture.
  13308. * @returns The texture
  13309. */
  13310. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13311. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13312. if (!this._caps.depthTextureExtension) {
  13313. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13314. return internalTexture;
  13315. }
  13316. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13317. var gl = this._gl;
  13318. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13319. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13320. if (this.webGLVersion > 1) {
  13321. if (internalOptions.generateStencil) {
  13322. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13323. }
  13324. else {
  13325. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13326. }
  13327. }
  13328. else {
  13329. if (internalOptions.generateStencil) {
  13330. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13331. }
  13332. else {
  13333. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13334. }
  13335. }
  13336. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13337. return internalTexture;
  13338. };
  13339. /**
  13340. * Creates a depth stencil cube texture.
  13341. * This is only available in WebGL 2.
  13342. * @param size The size of face edge in the cube texture.
  13343. * @param options The options defining the cube texture.
  13344. * @returns The cube texture
  13345. */
  13346. Engine.prototype.createDepthStencilCubeTexture = function (size, options) {
  13347. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13348. internalTexture.isCube = true;
  13349. if (this.webGLVersion === 1) {
  13350. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13351. return internalTexture;
  13352. }
  13353. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13354. var gl = this._gl;
  13355. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13356. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13357. // Create the depth/stencil buffer
  13358. for (var face = 0; face < 6; face++) {
  13359. if (internalOptions.generateStencil) {
  13360. 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);
  13361. }
  13362. else {
  13363. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13364. }
  13365. }
  13366. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13367. return internalTexture;
  13368. };
  13369. /**
  13370. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13371. * @param renderTarget The render target to set the frame buffer for
  13372. */
  13373. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13374. // Create the framebuffer
  13375. var internalTexture = renderTarget.getInternalTexture();
  13376. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13377. return;
  13378. }
  13379. var gl = this._gl;
  13380. var depthStencilTexture = renderTarget.depthStencilTexture;
  13381. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13382. if (depthStencilTexture.isCube) {
  13383. if (depthStencilTexture._generateStencilBuffer) {
  13384. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13385. }
  13386. else {
  13387. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13388. }
  13389. }
  13390. else {
  13391. if (depthStencilTexture._generateStencilBuffer) {
  13392. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13393. }
  13394. else {
  13395. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13396. }
  13397. }
  13398. this.bindUnboundFramebuffer(null);
  13399. };
  13400. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13401. var fullOptions = new RenderTargetCreationOptions();
  13402. if (options !== undefined && typeof options === "object") {
  13403. fullOptions.generateMipMaps = options.generateMipMaps;
  13404. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13405. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13406. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13407. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13408. }
  13409. else {
  13410. fullOptions.generateMipMaps = options;
  13411. fullOptions.generateDepthBuffer = true;
  13412. fullOptions.generateStencilBuffer = false;
  13413. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13414. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13415. }
  13416. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13417. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13418. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13419. }
  13420. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13421. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13422. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13423. }
  13424. var gl = this._gl;
  13425. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13426. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13427. var width = size.width || size;
  13428. var height = size.height || size;
  13429. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13430. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13431. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13432. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13433. }
  13434. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13435. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13436. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13437. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13438. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13439. // Create the framebuffer
  13440. var framebuffer = gl.createFramebuffer();
  13441. this.bindUnboundFramebuffer(framebuffer);
  13442. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13443. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13444. if (fullOptions.generateMipMaps) {
  13445. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13446. }
  13447. // Unbind
  13448. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13449. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13450. this.bindUnboundFramebuffer(null);
  13451. texture._framebuffer = framebuffer;
  13452. texture.baseWidth = width;
  13453. texture.baseHeight = height;
  13454. texture.width = width;
  13455. texture.height = height;
  13456. texture.isReady = true;
  13457. texture.samples = 1;
  13458. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13459. texture.samplingMode = fullOptions.samplingMode;
  13460. texture.type = fullOptions.type;
  13461. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13462. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13463. // this.resetTextureCache();
  13464. this._internalTexturesCache.push(texture);
  13465. return texture;
  13466. };
  13467. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13468. var generateMipMaps = false;
  13469. var generateDepthBuffer = true;
  13470. var generateStencilBuffer = false;
  13471. var generateDepthTexture = false;
  13472. var textureCount = 1;
  13473. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13474. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13475. var types = [], samplingModes = [];
  13476. if (options !== undefined) {
  13477. generateMipMaps = options.generateMipMaps;
  13478. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13479. generateStencilBuffer = options.generateStencilBuffer;
  13480. generateDepthTexture = options.generateDepthTexture;
  13481. textureCount = options.textureCount || 1;
  13482. if (options.types) {
  13483. types = options.types;
  13484. }
  13485. if (options.samplingModes) {
  13486. samplingModes = options.samplingModes;
  13487. }
  13488. }
  13489. var gl = this._gl;
  13490. // Create the framebuffer
  13491. var framebuffer = gl.createFramebuffer();
  13492. this.bindUnboundFramebuffer(framebuffer);
  13493. var width = size.width || size;
  13494. var height = size.height || size;
  13495. var textures = [];
  13496. var attachments = [];
  13497. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13498. for (var i = 0; i < textureCount; i++) {
  13499. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13500. var type = types[i] || defaultType;
  13501. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13502. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13503. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13504. }
  13505. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13506. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13507. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13508. }
  13509. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13510. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13511. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13512. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13513. }
  13514. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13515. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13516. textures.push(texture);
  13517. attachments.push(attachment);
  13518. gl.activeTexture(gl["TEXTURE" + i]);
  13519. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13520. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13521. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13522. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13523. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13524. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13525. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13526. if (generateMipMaps) {
  13527. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13528. }
  13529. // Unbind
  13530. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13531. texture._framebuffer = framebuffer;
  13532. texture._depthStencilBuffer = depthStencilBuffer;
  13533. texture.baseWidth = width;
  13534. texture.baseHeight = height;
  13535. texture.width = width;
  13536. texture.height = height;
  13537. texture.isReady = true;
  13538. texture.samples = 1;
  13539. texture.generateMipMaps = generateMipMaps;
  13540. texture.samplingMode = samplingMode;
  13541. texture.type = type;
  13542. texture._generateDepthBuffer = generateDepthBuffer;
  13543. texture._generateStencilBuffer = generateStencilBuffer;
  13544. texture._attachments = attachments;
  13545. this._internalTexturesCache.push(texture);
  13546. }
  13547. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13548. // Depth texture
  13549. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13550. gl.activeTexture(gl.TEXTURE0);
  13551. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13552. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13553. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13554. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13555. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13556. 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);
  13557. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13558. depthTexture._framebuffer = framebuffer;
  13559. depthTexture.baseWidth = width;
  13560. depthTexture.baseHeight = height;
  13561. depthTexture.width = width;
  13562. depthTexture.height = height;
  13563. depthTexture.isReady = true;
  13564. depthTexture.samples = 1;
  13565. depthTexture.generateMipMaps = generateMipMaps;
  13566. depthTexture.samplingMode = gl.NEAREST;
  13567. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13568. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13569. textures.push(depthTexture);
  13570. this._internalTexturesCache.push(depthTexture);
  13571. }
  13572. gl.drawBuffers(attachments);
  13573. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13574. this.bindUnboundFramebuffer(null);
  13575. this.resetTextureCache();
  13576. return textures;
  13577. };
  13578. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13579. if (samples === void 0) { samples = 1; }
  13580. var depthStencilBuffer = null;
  13581. var gl = this._gl;
  13582. // Create the depth/stencil buffer
  13583. if (generateStencilBuffer) {
  13584. depthStencilBuffer = gl.createRenderbuffer();
  13585. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13586. if (samples > 1) {
  13587. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13588. }
  13589. else {
  13590. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13591. }
  13592. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13593. }
  13594. else if (generateDepthBuffer) {
  13595. depthStencilBuffer = gl.createRenderbuffer();
  13596. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13597. if (samples > 1) {
  13598. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13599. }
  13600. else {
  13601. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13602. }
  13603. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13604. }
  13605. return depthStencilBuffer;
  13606. };
  13607. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13608. if (this.webGLVersion < 2 || !texture) {
  13609. return 1;
  13610. }
  13611. if (texture.samples === samples) {
  13612. return samples;
  13613. }
  13614. var gl = this._gl;
  13615. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13616. // Dispose previous render buffers
  13617. if (texture._depthStencilBuffer) {
  13618. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13619. texture._depthStencilBuffer = null;
  13620. }
  13621. if (texture._MSAAFramebuffer) {
  13622. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13623. texture._MSAAFramebuffer = null;
  13624. }
  13625. if (texture._MSAARenderBuffer) {
  13626. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13627. texture._MSAARenderBuffer = null;
  13628. }
  13629. if (samples > 1) {
  13630. var framebuffer = gl.createFramebuffer();
  13631. if (!framebuffer) {
  13632. throw new Error("Unable to create multi sampled framebuffer");
  13633. }
  13634. texture._MSAAFramebuffer = framebuffer;
  13635. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13636. var colorRenderbuffer = gl.createRenderbuffer();
  13637. if (!colorRenderbuffer) {
  13638. throw new Error("Unable to create multi sampled framebuffer");
  13639. }
  13640. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13641. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13642. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13643. texture._MSAARenderBuffer = colorRenderbuffer;
  13644. }
  13645. else {
  13646. this.bindUnboundFramebuffer(texture._framebuffer);
  13647. }
  13648. texture.samples = samples;
  13649. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13650. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13651. this.bindUnboundFramebuffer(null);
  13652. return samples;
  13653. };
  13654. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13655. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13656. return 1;
  13657. }
  13658. if (textures[0].samples === samples) {
  13659. return samples;
  13660. }
  13661. var gl = this._gl;
  13662. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13663. // Dispose previous render buffers
  13664. if (textures[0]._depthStencilBuffer) {
  13665. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13666. textures[0]._depthStencilBuffer = null;
  13667. }
  13668. if (textures[0]._MSAAFramebuffer) {
  13669. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13670. textures[0]._MSAAFramebuffer = null;
  13671. }
  13672. for (var i = 0; i < textures.length; i++) {
  13673. if (textures[i]._MSAARenderBuffer) {
  13674. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13675. textures[i]._MSAARenderBuffer = null;
  13676. }
  13677. }
  13678. if (samples > 1) {
  13679. var framebuffer = gl.createFramebuffer();
  13680. if (!framebuffer) {
  13681. throw new Error("Unable to create multi sampled framebuffer");
  13682. }
  13683. this.bindUnboundFramebuffer(framebuffer);
  13684. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13685. var attachments = [];
  13686. for (var i = 0; i < textures.length; i++) {
  13687. var texture = textures[i];
  13688. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13689. var colorRenderbuffer = gl.createRenderbuffer();
  13690. if (!colorRenderbuffer) {
  13691. throw new Error("Unable to create multi sampled framebuffer");
  13692. }
  13693. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13694. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13695. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13696. texture._MSAAFramebuffer = framebuffer;
  13697. texture._MSAARenderBuffer = colorRenderbuffer;
  13698. texture.samples = samples;
  13699. texture._depthStencilBuffer = depthStencilBuffer;
  13700. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13701. attachments.push(attachment);
  13702. }
  13703. gl.drawBuffers(attachments);
  13704. }
  13705. else {
  13706. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13707. }
  13708. this.bindUnboundFramebuffer(null);
  13709. return samples;
  13710. };
  13711. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13712. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13713. };
  13714. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13715. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13716. };
  13717. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13718. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE }, options);
  13719. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13720. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13721. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13722. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13723. }
  13724. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13725. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13726. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13727. }
  13728. var gl = this._gl;
  13729. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13730. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13731. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13732. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13733. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13734. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13735. }
  13736. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13737. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13738. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13739. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13740. for (var face = 0; face < 6; face++) {
  13741. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), size, size, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13742. }
  13743. // Create the framebuffer
  13744. var framebuffer = gl.createFramebuffer();
  13745. this.bindUnboundFramebuffer(framebuffer);
  13746. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  13747. // MipMaps
  13748. if (fullOptions.generateMipMaps) {
  13749. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13750. }
  13751. // Unbind
  13752. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13753. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13754. this.bindUnboundFramebuffer(null);
  13755. texture._framebuffer = framebuffer;
  13756. texture.width = size;
  13757. texture.height = size;
  13758. texture.isReady = true;
  13759. texture.isCube = true;
  13760. texture.samples = 1;
  13761. texture.generateMipMaps = fullOptions.generateMipMaps;
  13762. texture.samplingMode = fullOptions.samplingMode;
  13763. texture.type = fullOptions.type;
  13764. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13765. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  13766. this._internalTexturesCache.push(texture);
  13767. return texture;
  13768. };
  13769. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13770. var _this = this;
  13771. if (onLoad === void 0) { onLoad = null; }
  13772. if (onError === void 0) { onError = null; }
  13773. if (forcedExtension === void 0) { forcedExtension = null; }
  13774. var callback = function (loadData) {
  13775. if (!loadData) {
  13776. if (onLoad) {
  13777. onLoad(null);
  13778. }
  13779. return;
  13780. }
  13781. var texture = loadData.texture;
  13782. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13783. texture._lodGenerationScale = scale;
  13784. texture._lodGenerationOffset = offset;
  13785. if (_this._caps.textureLOD) {
  13786. // Do not add extra process if texture lod is supported.
  13787. if (onLoad) {
  13788. onLoad(texture);
  13789. }
  13790. return;
  13791. }
  13792. var mipSlices = 3;
  13793. var gl = _this._gl;
  13794. var width = loadData.width;
  13795. if (!width) {
  13796. return;
  13797. }
  13798. var textures = [];
  13799. for (var i = 0; i < mipSlices; i++) {
  13800. //compute LOD from even spacing in smoothness (matching shader calculation)
  13801. var smoothness = i / (mipSlices - 1);
  13802. var roughness = 1 - smoothness;
  13803. var minLODIndex = offset; // roughness = 0
  13804. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13805. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13806. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13807. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13808. glTextureFromLod.isCube = true;
  13809. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  13810. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13811. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13812. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13813. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13814. if (loadData.isDDS) {
  13815. var info = loadData.info;
  13816. var data = loadData.data;
  13817. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13818. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  13819. }
  13820. else {
  13821. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  13822. }
  13823. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13824. // Wrap in a base texture for easy binding.
  13825. var lodTexture = new BABYLON.BaseTexture(scene);
  13826. lodTexture.isCube = true;
  13827. lodTexture._texture = glTextureFromLod;
  13828. glTextureFromLod.isReady = true;
  13829. textures.push(lodTexture);
  13830. }
  13831. texture._lodTextureHigh = textures[2];
  13832. texture._lodTextureMid = textures[1];
  13833. texture._lodTextureLow = textures[0];
  13834. if (onLoad) {
  13835. onLoad(texture);
  13836. }
  13837. };
  13838. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  13839. };
  13840. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  13841. var _this = this;
  13842. if (onLoad === void 0) { onLoad = null; }
  13843. if (onError === void 0) { onError = null; }
  13844. if (forcedExtension === void 0) { forcedExtension = null; }
  13845. var gl = this._gl;
  13846. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  13847. texture.isCube = true;
  13848. texture.url = rootUrl;
  13849. texture.generateMipMaps = !noMipmap;
  13850. if (!this._doNotHandleContextLost) {
  13851. texture._extension = forcedExtension;
  13852. texture._files = files;
  13853. }
  13854. var isKTX = false;
  13855. var isDDS = false;
  13856. var lastDot = rootUrl.lastIndexOf('.');
  13857. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  13858. if (this._textureFormatInUse) {
  13859. extension = this._textureFormatInUse;
  13860. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  13861. isKTX = true;
  13862. }
  13863. else {
  13864. isDDS = (extension === ".dds");
  13865. }
  13866. var onerror = function (request, exception) {
  13867. if (onError && request) {
  13868. onError(request.status + " " + request.statusText, exception);
  13869. }
  13870. };
  13871. if (isKTX) {
  13872. this._loadFile(rootUrl, function (data) {
  13873. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  13874. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  13875. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13876. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  13877. ktx.uploadLevels(_this._gl, !noMipmap);
  13878. _this.setCubeMapTextureParams(gl, loadMipmap);
  13879. texture.width = ktx.pixelWidth;
  13880. texture.height = ktx.pixelHeight;
  13881. texture.isReady = true;
  13882. }, undefined, undefined, true, onerror);
  13883. }
  13884. else if (isDDS) {
  13885. if (files && files.length === 6) {
  13886. this._cascadeLoadFiles(scene, function (imgs) {
  13887. var info;
  13888. var loadMipmap = false;
  13889. var width = 0;
  13890. for (var index = 0; index < imgs.length; index++) {
  13891. var data = imgs[index];
  13892. info = BABYLON.DDSTools.GetDDSInfo(data);
  13893. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13894. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13895. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13896. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  13897. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13898. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13899. }
  13900. texture.width = info.width;
  13901. texture.height = info.height;
  13902. texture.type = info.textureType;
  13903. width = info.width;
  13904. }
  13905. _this.setCubeMapTextureParams(gl, loadMipmap);
  13906. texture.isReady = true;
  13907. if (onLoad) {
  13908. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  13909. }
  13910. }, files, onError);
  13911. }
  13912. else {
  13913. this._loadFile(rootUrl, function (data) {
  13914. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13915. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13916. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13917. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13918. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  13919. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13920. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13921. }
  13922. _this.setCubeMapTextureParams(gl, loadMipmap);
  13923. texture.width = info.width;
  13924. texture.height = info.height;
  13925. texture.isReady = true;
  13926. texture.type = info.textureType;
  13927. if (onLoad) {
  13928. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  13929. }
  13930. }, undefined, undefined, true, onerror);
  13931. }
  13932. }
  13933. else {
  13934. if (!files) {
  13935. throw new Error("Cannot load cubemap because files were not defined");
  13936. }
  13937. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  13938. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  13939. var height = width;
  13940. _this._prepareWorkingCanvas();
  13941. if (!_this._workingCanvas || !_this._workingContext) {
  13942. return;
  13943. }
  13944. _this._workingCanvas.width = width;
  13945. _this._workingCanvas.height = height;
  13946. var faces = [
  13947. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  13948. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  13949. ];
  13950. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13951. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13952. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  13953. for (var index = 0; index < faces.length; index++) {
  13954. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  13955. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  13956. }
  13957. if (!noMipmap) {
  13958. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13959. }
  13960. _this.setCubeMapTextureParams(gl, !noMipmap);
  13961. texture.width = width;
  13962. texture.height = height;
  13963. texture.isReady = true;
  13964. if (format) {
  13965. texture.format = format;
  13966. }
  13967. texture.onLoadedObservable.notifyObservers(texture);
  13968. texture.onLoadedObservable.clear();
  13969. if (onLoad) {
  13970. onLoad();
  13971. }
  13972. }, files, onError);
  13973. }
  13974. this._internalTexturesCache.push(texture);
  13975. return texture;
  13976. };
  13977. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  13978. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13979. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  13980. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13981. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13982. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13983. // this.resetTextureCache();
  13984. };
  13985. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  13986. if (compression === void 0) { compression = null; }
  13987. if (level === void 0) { level = 0; }
  13988. texture._bufferViewArray = data;
  13989. texture.format = format;
  13990. texture.type = type;
  13991. texture.invertY = invertY;
  13992. texture._compression = compression;
  13993. var gl = this._gl;
  13994. var textureType = this._getWebGLTextureType(type);
  13995. var internalFormat = this._getInternalFormat(format);
  13996. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  13997. var needConversion = false;
  13998. if (internalFormat === gl.RGB) {
  13999. internalFormat = gl.RGBA;
  14000. needConversion = true;
  14001. }
  14002. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14003. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14004. if (texture.width % 4 !== 0) {
  14005. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14006. }
  14007. // Data are known to be in +X +Y +Z -X -Y -Z
  14008. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14009. var faceData = data[faceIndex];
  14010. if (compression) {
  14011. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14012. }
  14013. else {
  14014. if (needConversion) {
  14015. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14016. }
  14017. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14018. }
  14019. }
  14020. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14021. if (isPot && texture.generateMipMaps && level === 0) {
  14022. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14023. }
  14024. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14025. // this.resetTextureCache();
  14026. texture.isReady = true;
  14027. };
  14028. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14029. if (compression === void 0) { compression = null; }
  14030. var gl = this._gl;
  14031. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14032. texture.isCube = true;
  14033. texture.generateMipMaps = generateMipMaps;
  14034. texture.format = format;
  14035. texture.type = type;
  14036. if (!this._doNotHandleContextLost) {
  14037. texture._bufferViewArray = data;
  14038. }
  14039. var textureType = this._getWebGLTextureType(type);
  14040. var internalFormat = this._getInternalFormat(format);
  14041. if (internalFormat === gl.RGB) {
  14042. internalFormat = gl.RGBA;
  14043. }
  14044. var width = size;
  14045. var height = width;
  14046. texture.width = width;
  14047. texture.height = height;
  14048. // Double check on POT to generate Mips.
  14049. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14050. if (!isPot) {
  14051. generateMipMaps = false;
  14052. }
  14053. // Upload data if needed. The texture won't be ready until then.
  14054. if (data) {
  14055. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14056. }
  14057. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14058. // Filters
  14059. if (data && generateMipMaps) {
  14060. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14061. }
  14062. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14063. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14064. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14065. }
  14066. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14067. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14068. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14069. }
  14070. else {
  14071. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14072. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14073. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14074. }
  14075. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14076. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14077. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14078. return texture;
  14079. };
  14080. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14081. var _this = this;
  14082. if (onLoad === void 0) { onLoad = null; }
  14083. if (onError === void 0) { onError = null; }
  14084. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14085. if (invertY === void 0) { invertY = false; }
  14086. var gl = this._gl;
  14087. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14088. scene._addPendingData(texture);
  14089. texture.url = url;
  14090. this._internalTexturesCache.push(texture);
  14091. var onerror = function (request, exception) {
  14092. scene._removePendingData(texture);
  14093. if (onError && request) {
  14094. onError(request.status + " " + request.statusText, exception);
  14095. }
  14096. };
  14097. var internalCallback = function (data) {
  14098. var width = texture.width;
  14099. var faceDataArrays = callback(data);
  14100. if (!faceDataArrays) {
  14101. return;
  14102. }
  14103. if (mipmmapGenerator) {
  14104. var textureType = _this._getWebGLTextureType(type);
  14105. var internalFormat = _this._getInternalFormat(format);
  14106. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14107. var needConversion = false;
  14108. if (internalFormat === gl.RGB) {
  14109. internalFormat = gl.RGBA;
  14110. needConversion = true;
  14111. }
  14112. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14113. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14114. var mipData = mipmmapGenerator(faceDataArrays);
  14115. for (var level = 0; level < mipData.length; level++) {
  14116. var mipSize = width >> level;
  14117. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14118. var mipFaceData = mipData[level][faceIndex];
  14119. if (needConversion) {
  14120. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14121. }
  14122. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14123. }
  14124. }
  14125. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14126. }
  14127. else {
  14128. texture.generateMipMaps = !noMipmap;
  14129. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14130. }
  14131. texture.isReady = true;
  14132. // this.resetTextureCache();
  14133. scene._removePendingData(texture);
  14134. if (onLoad) {
  14135. onLoad();
  14136. }
  14137. };
  14138. this._loadFile(url, function (data) {
  14139. internalCallback(data);
  14140. }, undefined, scene.database, true, onerror);
  14141. return texture;
  14142. };
  14143. ;
  14144. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14145. if (compression === void 0) { compression = null; }
  14146. var internalFormat = this._getInternalFormat(format);
  14147. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14148. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14149. if (!this._doNotHandleContextLost) {
  14150. texture._bufferView = data;
  14151. texture.format = format;
  14152. texture.invertY = invertY;
  14153. texture._compression = compression;
  14154. }
  14155. if (texture.width % 4 !== 0) {
  14156. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14157. }
  14158. if (compression && data) {
  14159. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14160. }
  14161. else {
  14162. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14163. }
  14164. if (texture.generateMipMaps) {
  14165. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14166. }
  14167. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14168. // this.resetTextureCache();
  14169. texture.isReady = true;
  14170. };
  14171. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14172. if (compression === void 0) { compression = null; }
  14173. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14174. texture.baseWidth = width;
  14175. texture.baseHeight = height;
  14176. texture.baseDepth = depth;
  14177. texture.width = width;
  14178. texture.height = height;
  14179. texture.depth = depth;
  14180. texture.format = format;
  14181. texture.generateMipMaps = generateMipMaps;
  14182. texture.samplingMode = samplingMode;
  14183. texture.is3D = true;
  14184. if (!this._doNotHandleContextLost) {
  14185. texture._bufferView = data;
  14186. }
  14187. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14188. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14189. // Filters
  14190. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14191. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14192. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14193. if (generateMipMaps) {
  14194. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14195. }
  14196. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14197. this._internalTexturesCache.push(texture);
  14198. return texture;
  14199. };
  14200. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14201. var gl = this._gl;
  14202. if (!gl) {
  14203. return;
  14204. }
  14205. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14206. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14207. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14208. if (!noMipmap && !isCompressed) {
  14209. gl.generateMipmap(gl.TEXTURE_2D);
  14210. }
  14211. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14212. // this.resetTextureCache();
  14213. if (scene) {
  14214. scene._removePendingData(texture);
  14215. }
  14216. texture.onLoadedObservable.notifyObservers(texture);
  14217. texture.onLoadedObservable.clear();
  14218. };
  14219. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14220. var _this = this;
  14221. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14222. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14223. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14224. var gl = this._gl;
  14225. if (!gl) {
  14226. return;
  14227. }
  14228. if (!texture._webGLTexture) {
  14229. // this.resetTextureCache();
  14230. if (scene) {
  14231. scene._removePendingData(texture);
  14232. }
  14233. return;
  14234. }
  14235. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14236. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14237. texture.baseWidth = width;
  14238. texture.baseHeight = height;
  14239. texture.width = potWidth;
  14240. texture.height = potHeight;
  14241. texture.isReady = true;
  14242. if (processFunction(potWidth, potHeight, function () {
  14243. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14244. })) {
  14245. // Returning as texture needs extra async steps
  14246. return;
  14247. }
  14248. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14249. };
  14250. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14251. // Create new RGBA data container.
  14252. var rgbaData;
  14253. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14254. rgbaData = new Float32Array(width * height * 4);
  14255. }
  14256. else {
  14257. rgbaData = new Uint32Array(width * height * 4);
  14258. }
  14259. // Convert each pixel.
  14260. for (var x = 0; x < width; x++) {
  14261. for (var y = 0; y < height; y++) {
  14262. var index = (y * width + x) * 3;
  14263. var newIndex = (y * width + x) * 4;
  14264. // Map Old Value to new value.
  14265. rgbaData[newIndex + 0] = rgbData[index + 0];
  14266. rgbaData[newIndex + 1] = rgbData[index + 1];
  14267. rgbaData[newIndex + 2] = rgbData[index + 2];
  14268. // Add fully opaque alpha channel.
  14269. rgbaData[newIndex + 3] = 1;
  14270. }
  14271. }
  14272. return rgbaData;
  14273. };
  14274. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14275. var gl = this._gl;
  14276. if (texture._framebuffer) {
  14277. gl.deleteFramebuffer(texture._framebuffer);
  14278. texture._framebuffer = null;
  14279. }
  14280. if (texture._depthStencilBuffer) {
  14281. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14282. texture._depthStencilBuffer = null;
  14283. }
  14284. if (texture._MSAAFramebuffer) {
  14285. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14286. texture._MSAAFramebuffer = null;
  14287. }
  14288. if (texture._MSAARenderBuffer) {
  14289. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14290. texture._MSAARenderBuffer = null;
  14291. }
  14292. };
  14293. Engine.prototype._releaseTexture = function (texture) {
  14294. var gl = this._gl;
  14295. this._releaseFramebufferObjects(texture);
  14296. gl.deleteTexture(texture._webGLTexture);
  14297. // Unbind channels
  14298. this.unbindAllTextures();
  14299. var index = this._internalTexturesCache.indexOf(texture);
  14300. if (index !== -1) {
  14301. this._internalTexturesCache.splice(index, 1);
  14302. }
  14303. // Integrated fixed lod samplers.
  14304. if (texture._lodTextureHigh) {
  14305. texture._lodTextureHigh.dispose();
  14306. }
  14307. if (texture._lodTextureMid) {
  14308. texture._lodTextureMid.dispose();
  14309. }
  14310. if (texture._lodTextureLow) {
  14311. texture._lodTextureLow.dispose();
  14312. }
  14313. };
  14314. Engine.prototype.setProgram = function (program) {
  14315. if (this._currentProgram !== program) {
  14316. this._gl.useProgram(program);
  14317. this._currentProgram = program;
  14318. }
  14319. };
  14320. Engine.prototype.bindSamplers = function (effect) {
  14321. this.setProgram(effect.getProgram());
  14322. var samplers = effect.getSamplers();
  14323. for (var index = 0; index < samplers.length; index++) {
  14324. var uniform = effect.getUniform(samplers[index]);
  14325. if (uniform) {
  14326. this._boundUniforms[index] = uniform;
  14327. }
  14328. }
  14329. this._currentEffect = null;
  14330. };
  14331. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14332. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14333. return;
  14334. }
  14335. // Remove
  14336. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14337. // Bind last to it
  14338. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14339. // Bind to dummy
  14340. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14341. };
  14342. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14343. if (!internalTexture) {
  14344. return -1;
  14345. }
  14346. internalTexture._initialSlot = channel;
  14347. if (this.disableTextureBindingOptimization) {
  14348. if (channel !== internalTexture._designatedSlot) {
  14349. this._textureCollisions.addCount(1, false);
  14350. }
  14351. }
  14352. else {
  14353. if (channel !== internalTexture._designatedSlot) {
  14354. if (internalTexture._designatedSlot > -1) {
  14355. return internalTexture._designatedSlot;
  14356. }
  14357. else {
  14358. // No slot for this texture, let's pick a new one (if we find a free slot)
  14359. if (this._nextFreeTextureSlots.length) {
  14360. return this._nextFreeTextureSlots[0];
  14361. }
  14362. // We need to recycle the oldest bound texture, sorry.
  14363. this._textureCollisions.addCount(1, false);
  14364. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14365. }
  14366. }
  14367. }
  14368. return channel;
  14369. };
  14370. Engine.prototype._linkTrackers = function (previous, next) {
  14371. previous.next = next;
  14372. next.previous = previous;
  14373. };
  14374. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14375. var currentSlot = internalTexture._designatedSlot;
  14376. if (currentSlot === -1) {
  14377. return -1;
  14378. }
  14379. internalTexture._designatedSlot = -1;
  14380. if (this.disableTextureBindingOptimization) {
  14381. return -1;
  14382. }
  14383. // Remove from bound list
  14384. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14385. // Free the slot
  14386. this._boundTexturesCache[currentSlot] = null;
  14387. this._nextFreeTextureSlots.push(currentSlot);
  14388. return currentSlot;
  14389. };
  14390. Engine.prototype._activateCurrentTexture = function () {
  14391. if (this._currentTextureChannel !== this._activeChannel) {
  14392. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14393. this._currentTextureChannel = this._activeChannel;
  14394. }
  14395. };
  14396. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14397. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14398. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14399. this._activeChannel = texture._designatedSlot;
  14400. }
  14401. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14402. var isTextureForRendering = texture && texture._initialSlot > -1;
  14403. if (currentTextureBound !== texture) {
  14404. if (currentTextureBound) {
  14405. this._removeDesignatedSlot(currentTextureBound);
  14406. }
  14407. this._activateCurrentTexture();
  14408. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14409. this._boundTexturesCache[this._activeChannel] = texture;
  14410. if (texture) {
  14411. if (!this.disableTextureBindingOptimization) {
  14412. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14413. if (slotIndex > -1) {
  14414. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14415. }
  14416. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14417. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14418. }
  14419. texture._designatedSlot = this._activeChannel;
  14420. }
  14421. }
  14422. else if (forTextureDataUpdate) {
  14423. this._activateCurrentTexture();
  14424. }
  14425. if (isTextureForRendering && !forTextureDataUpdate) {
  14426. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14427. }
  14428. };
  14429. Engine.prototype._bindTexture = function (channel, texture) {
  14430. if (channel < 0) {
  14431. return;
  14432. }
  14433. if (texture) {
  14434. channel = this._getCorrectTextureChannel(channel, texture);
  14435. }
  14436. this._activeChannel = channel;
  14437. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14438. };
  14439. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14440. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14441. };
  14442. Engine.prototype.unbindAllTextures = function () {
  14443. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14444. this._activeChannel = channel;
  14445. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14446. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14447. if (this.webGLVersion > 1) {
  14448. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14449. }
  14450. }
  14451. };
  14452. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14453. if (channel < 0) {
  14454. return;
  14455. }
  14456. if (uniform) {
  14457. this._boundUniforms[channel] = uniform;
  14458. }
  14459. this._setTexture(channel, texture);
  14460. };
  14461. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14462. var uniform = this._boundUniforms[sourceSlot];
  14463. if (uniform._currentState === destination) {
  14464. return;
  14465. }
  14466. this._gl.uniform1i(uniform, destination);
  14467. uniform._currentState = destination;
  14468. };
  14469. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  14470. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14471. // Not ready?
  14472. if (!texture) {
  14473. if (this._boundTexturesCache[channel] != null) {
  14474. this._activeChannel = channel;
  14475. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14476. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14477. if (this.webGLVersion > 1) {
  14478. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14479. }
  14480. }
  14481. return false;
  14482. }
  14483. // Video
  14484. if (texture.video) {
  14485. this._activeChannel = channel;
  14486. texture.update();
  14487. }
  14488. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14489. texture.delayLoad();
  14490. return false;
  14491. }
  14492. var internalTexture;
  14493. if (texture.isReady()) {
  14494. internalTexture = texture.getInternalTexture();
  14495. }
  14496. else if (texture.isCube) {
  14497. internalTexture = this.emptyCubeTexture;
  14498. }
  14499. else if (texture.is3D) {
  14500. internalTexture = this.emptyTexture3D;
  14501. }
  14502. else {
  14503. internalTexture = this.emptyTexture;
  14504. }
  14505. if (!isPartOfTextureArray) {
  14506. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14507. }
  14508. if (this._boundTexturesCache[channel] === internalTexture) {
  14509. this._moveBoundTextureOnTop(internalTexture);
  14510. if (!isPartOfTextureArray) {
  14511. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14512. }
  14513. return false;
  14514. }
  14515. this._activeChannel = channel;
  14516. if (internalTexture && internalTexture.is3D) {
  14517. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14518. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14519. internalTexture._cachedWrapU = texture.wrapU;
  14520. switch (texture.wrapU) {
  14521. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14522. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14523. break;
  14524. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14525. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14526. break;
  14527. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14528. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14529. break;
  14530. }
  14531. }
  14532. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14533. internalTexture._cachedWrapV = texture.wrapV;
  14534. switch (texture.wrapV) {
  14535. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14536. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14537. break;
  14538. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14539. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14540. break;
  14541. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14542. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14543. break;
  14544. }
  14545. }
  14546. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14547. internalTexture._cachedWrapR = texture.wrapR;
  14548. switch (texture.wrapR) {
  14549. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14550. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14551. break;
  14552. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14553. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14554. break;
  14555. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14556. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14557. break;
  14558. }
  14559. }
  14560. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14561. }
  14562. else if (internalTexture && internalTexture.isCube) {
  14563. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14564. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14565. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14566. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14567. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14568. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14569. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14570. }
  14571. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14572. }
  14573. else {
  14574. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14575. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14576. internalTexture._cachedWrapU = texture.wrapU;
  14577. switch (texture.wrapU) {
  14578. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14579. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14580. break;
  14581. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14582. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14583. break;
  14584. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14585. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14586. break;
  14587. }
  14588. }
  14589. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14590. internalTexture._cachedWrapV = texture.wrapV;
  14591. switch (texture.wrapV) {
  14592. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14593. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14594. break;
  14595. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14596. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14597. break;
  14598. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14599. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14600. break;
  14601. }
  14602. }
  14603. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14604. }
  14605. return true;
  14606. };
  14607. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14608. if (channel < 0 || !uniform) {
  14609. return;
  14610. }
  14611. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14612. this._textureUnits = new Int32Array(textures.length);
  14613. }
  14614. for (var i = 0; i < textures.length; i++) {
  14615. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14616. }
  14617. this._gl.uniform1iv(uniform, this._textureUnits);
  14618. for (var index = 0; index < textures.length; index++) {
  14619. this._setTexture(this._textureUnits[index], textures[index], true);
  14620. }
  14621. };
  14622. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14623. var internalTexture = texture.getInternalTexture();
  14624. if (!internalTexture) {
  14625. return;
  14626. }
  14627. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14628. var value = texture.anisotropicFilteringLevel;
  14629. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14630. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14631. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14632. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14633. }
  14634. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14635. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14636. internalTexture._cachedAnisotropicFilteringLevel = value;
  14637. }
  14638. };
  14639. Engine.prototype.readPixels = function (x, y, width, height) {
  14640. var data = new Uint8Array(height * width * 4);
  14641. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14642. return data;
  14643. };
  14644. /**
  14645. * Add an externaly attached data from its key.
  14646. * This method call will fail and return false, if such key already exists.
  14647. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14648. * @param key the unique key that identifies the data
  14649. * @param data the data object to associate to the key for this Engine instance
  14650. * @return true if no such key were already present and the data was added successfully, false otherwise
  14651. */
  14652. Engine.prototype.addExternalData = function (key, data) {
  14653. if (!this._externalData) {
  14654. this._externalData = new BABYLON.StringDictionary();
  14655. }
  14656. return this._externalData.add(key, data);
  14657. };
  14658. /**
  14659. * Get an externaly attached data from its key
  14660. * @param key the unique key that identifies the data
  14661. * @return the associated data, if present (can be null), or undefined if not present
  14662. */
  14663. Engine.prototype.getExternalData = function (key) {
  14664. if (!this._externalData) {
  14665. this._externalData = new BABYLON.StringDictionary();
  14666. }
  14667. return this._externalData.get(key);
  14668. };
  14669. /**
  14670. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14671. * @param key the unique key that identifies the data
  14672. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14673. * @return the associated data, can be null if the factory returned null.
  14674. */
  14675. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14676. if (!this._externalData) {
  14677. this._externalData = new BABYLON.StringDictionary();
  14678. }
  14679. return this._externalData.getOrAddWithFactory(key, factory);
  14680. };
  14681. /**
  14682. * Remove an externaly attached data from the Engine instance
  14683. * @param key the unique key that identifies the data
  14684. * @return true if the data was successfully removed, false if it doesn't exist
  14685. */
  14686. Engine.prototype.removeExternalData = function (key) {
  14687. if (!this._externalData) {
  14688. this._externalData = new BABYLON.StringDictionary();
  14689. }
  14690. return this._externalData.remove(key);
  14691. };
  14692. Engine.prototype.unbindAllAttributes = function () {
  14693. if (this._mustWipeVertexAttributes) {
  14694. this._mustWipeVertexAttributes = false;
  14695. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14696. this._gl.disableVertexAttribArray(i);
  14697. this._vertexAttribArraysEnabled[i] = false;
  14698. this._currentBufferPointers[i].active = false;
  14699. }
  14700. return;
  14701. }
  14702. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14703. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14704. continue;
  14705. }
  14706. this._gl.disableVertexAttribArray(i);
  14707. this._vertexAttribArraysEnabled[i] = false;
  14708. this._currentBufferPointers[i].active = false;
  14709. }
  14710. };
  14711. Engine.prototype.releaseEffects = function () {
  14712. for (var name in this._compiledEffects) {
  14713. this._deleteProgram(this._compiledEffects[name]._program);
  14714. }
  14715. this._compiledEffects = {};
  14716. };
  14717. // Dispose
  14718. Engine.prototype.dispose = function () {
  14719. this.hideLoadingUI();
  14720. this.stopRenderLoop();
  14721. // Release postProcesses
  14722. while (this.postProcesses.length) {
  14723. this.postProcesses[0].dispose();
  14724. }
  14725. // Empty texture
  14726. if (this._emptyTexture) {
  14727. this._releaseTexture(this._emptyTexture);
  14728. this._emptyTexture = null;
  14729. }
  14730. if (this._emptyCubeTexture) {
  14731. this._releaseTexture(this._emptyCubeTexture);
  14732. this._emptyCubeTexture = null;
  14733. }
  14734. // Rescale PP
  14735. if (this._rescalePostProcess) {
  14736. this._rescalePostProcess.dispose();
  14737. }
  14738. // Release scenes
  14739. while (this.scenes.length) {
  14740. this.scenes[0].dispose();
  14741. }
  14742. // Release audio engine
  14743. if (Engine.audioEngine) {
  14744. Engine.audioEngine.dispose();
  14745. }
  14746. // Release effects
  14747. this.releaseEffects();
  14748. // Unbind
  14749. this.unbindAllAttributes();
  14750. if (this._dummyFramebuffer) {
  14751. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14752. }
  14753. //WebVR
  14754. this.disableVR();
  14755. // Events
  14756. if (BABYLON.Tools.IsWindowObjectExist()) {
  14757. window.removeEventListener("blur", this._onBlur);
  14758. window.removeEventListener("focus", this._onFocus);
  14759. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  14760. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  14761. if (this._renderingCanvas) {
  14762. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  14763. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  14764. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  14765. if (!this._doNotHandleContextLost) {
  14766. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  14767. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  14768. }
  14769. }
  14770. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  14771. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  14772. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  14773. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  14774. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  14775. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  14776. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  14777. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  14778. if (this._onVrDisplayConnect) {
  14779. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  14780. if (this._onVrDisplayDisconnect) {
  14781. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  14782. }
  14783. if (this._onVrDisplayPresentChange) {
  14784. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  14785. }
  14786. this._onVrDisplayConnect = null;
  14787. this._onVrDisplayDisconnect = null;
  14788. }
  14789. }
  14790. // Remove from Instances
  14791. var index = Engine.Instances.indexOf(this);
  14792. if (index >= 0) {
  14793. Engine.Instances.splice(index, 1);
  14794. }
  14795. this._workingCanvas = null;
  14796. this._workingContext = null;
  14797. this._currentBufferPointers = [];
  14798. this._renderingCanvas = null;
  14799. this._currentProgram = null;
  14800. this.onResizeObservable.clear();
  14801. this.onCanvasBlurObservable.clear();
  14802. this.onCanvasFocusObservable.clear();
  14803. this.onCanvasPointerOutObservable.clear();
  14804. this.onBeginFrameObservable.clear();
  14805. this.onEndFrameObservable.clear();
  14806. BABYLON.Effect.ResetCache();
  14807. // Abort active requests
  14808. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  14809. var request = _a[_i];
  14810. request.abort();
  14811. }
  14812. };
  14813. // Loading screen
  14814. Engine.prototype.displayLoadingUI = function () {
  14815. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14816. return;
  14817. }
  14818. var loadingScreen = this.loadingScreen;
  14819. if (loadingScreen) {
  14820. loadingScreen.displayLoadingUI();
  14821. }
  14822. };
  14823. Engine.prototype.hideLoadingUI = function () {
  14824. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14825. return;
  14826. }
  14827. var loadingScreen = this.loadingScreen;
  14828. if (loadingScreen) {
  14829. loadingScreen.hideLoadingUI();
  14830. }
  14831. };
  14832. Object.defineProperty(Engine.prototype, "loadingScreen", {
  14833. get: function () {
  14834. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  14835. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  14836. return this._loadingScreen;
  14837. },
  14838. set: function (loadingScreen) {
  14839. this._loadingScreen = loadingScreen;
  14840. },
  14841. enumerable: true,
  14842. configurable: true
  14843. });
  14844. Object.defineProperty(Engine.prototype, "loadingUIText", {
  14845. set: function (text) {
  14846. this.loadingScreen.loadingUIText = text;
  14847. },
  14848. enumerable: true,
  14849. configurable: true
  14850. });
  14851. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  14852. set: function (color) {
  14853. this.loadingScreen.loadingUIBackgroundColor = color;
  14854. },
  14855. enumerable: true,
  14856. configurable: true
  14857. });
  14858. Engine.prototype.attachContextLostEvent = function (callback) {
  14859. if (this._renderingCanvas) {
  14860. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  14861. }
  14862. };
  14863. Engine.prototype.attachContextRestoredEvent = function (callback) {
  14864. if (this._renderingCanvas) {
  14865. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  14866. }
  14867. };
  14868. Engine.prototype.getVertexShaderSource = function (program) {
  14869. var shaders = this._gl.getAttachedShaders(program);
  14870. if (!shaders) {
  14871. return null;
  14872. }
  14873. return this._gl.getShaderSource(shaders[0]);
  14874. };
  14875. Engine.prototype.getFragmentShaderSource = function (program) {
  14876. var shaders = this._gl.getAttachedShaders(program);
  14877. if (!shaders) {
  14878. return null;
  14879. }
  14880. return this._gl.getShaderSource(shaders[1]);
  14881. };
  14882. Engine.prototype.getError = function () {
  14883. return this._gl.getError();
  14884. };
  14885. // FPS
  14886. Engine.prototype.getFps = function () {
  14887. return this._fps;
  14888. };
  14889. Engine.prototype.getDeltaTime = function () {
  14890. return this._deltaTime;
  14891. };
  14892. Engine.prototype._measureFps = function () {
  14893. this._performanceMonitor.sampleFrame();
  14894. this._fps = this._performanceMonitor.averageFPS;
  14895. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  14896. };
  14897. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  14898. if (faceIndex === void 0) { faceIndex = -1; }
  14899. var gl = this._gl;
  14900. if (!this._dummyFramebuffer) {
  14901. var dummy = gl.createFramebuffer();
  14902. if (!dummy) {
  14903. throw new Error("Unable to create dummy framebuffer");
  14904. }
  14905. this._dummyFramebuffer = dummy;
  14906. }
  14907. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  14908. if (faceIndex > -1) {
  14909. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  14910. }
  14911. else {
  14912. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14913. }
  14914. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  14915. var buffer;
  14916. switch (readType) {
  14917. case gl.UNSIGNED_BYTE:
  14918. buffer = new Uint8Array(4 * width * height);
  14919. readType = gl.UNSIGNED_BYTE;
  14920. break;
  14921. default:
  14922. buffer = new Float32Array(4 * width * height);
  14923. readType = gl.FLOAT;
  14924. break;
  14925. }
  14926. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  14927. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  14928. return buffer;
  14929. };
  14930. Engine.prototype._canRenderToFloatFramebuffer = function () {
  14931. if (this._webGLVersion > 1) {
  14932. return this._caps.colorBufferFloat;
  14933. }
  14934. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  14935. };
  14936. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  14937. if (this._webGLVersion > 1) {
  14938. return this._caps.colorBufferFloat;
  14939. }
  14940. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  14941. };
  14942. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  14943. Engine.prototype._canRenderToFramebuffer = function (type) {
  14944. var gl = this._gl;
  14945. //clear existing errors
  14946. while (gl.getError() !== gl.NO_ERROR) { }
  14947. var successful = true;
  14948. var texture = gl.createTexture();
  14949. gl.bindTexture(gl.TEXTURE_2D, texture);
  14950. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  14951. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14952. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14953. var fb = gl.createFramebuffer();
  14954. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  14955. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  14956. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  14957. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  14958. successful = successful && (gl.getError() === gl.NO_ERROR);
  14959. //try render by clearing frame buffer's color buffer
  14960. if (successful) {
  14961. gl.clear(gl.COLOR_BUFFER_BIT);
  14962. successful = successful && (gl.getError() === gl.NO_ERROR);
  14963. }
  14964. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  14965. if (successful) {
  14966. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  14967. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14968. var readFormat = gl.RGBA;
  14969. var readType = gl.UNSIGNED_BYTE;
  14970. var buffer = new Uint8Array(4);
  14971. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  14972. successful = successful && (gl.getError() === gl.NO_ERROR);
  14973. }
  14974. //clean up
  14975. gl.deleteTexture(texture);
  14976. gl.deleteFramebuffer(fb);
  14977. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14978. //clear accumulated errors
  14979. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  14980. return successful;
  14981. };
  14982. Engine.prototype._getWebGLTextureType = function (type) {
  14983. if (type === Engine.TEXTURETYPE_FLOAT) {
  14984. return this._gl.FLOAT;
  14985. }
  14986. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14987. // Add Half Float Constant.
  14988. return this._gl.HALF_FLOAT_OES;
  14989. }
  14990. return this._gl.UNSIGNED_BYTE;
  14991. };
  14992. ;
  14993. /** @ignore */
  14994. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  14995. if (this._webGLVersion === 1) {
  14996. return this._gl.RGBA;
  14997. }
  14998. if (type === Engine.TEXTURETYPE_FLOAT) {
  14999. if (format) {
  15000. switch (format) {
  15001. case Engine.TEXTUREFORMAT_R32F:
  15002. return this._gl.R32F;
  15003. case Engine.TEXTUREFORMAT_RG32F:
  15004. return this._gl.RG32F;
  15005. case Engine.TEXTUREFORMAT_RGB32F:
  15006. return this._gl.RGB32F;
  15007. }
  15008. }
  15009. return this._gl.RGBA32F;
  15010. }
  15011. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15012. return this._gl.RGBA16F;
  15013. }
  15014. return this._gl.RGBA;
  15015. };
  15016. ;
  15017. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15018. if (type === Engine.TEXTURETYPE_FLOAT) {
  15019. return this._gl.RGBA32F;
  15020. }
  15021. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15022. return this._gl.RGBA16F;
  15023. }
  15024. return this._gl.RGBA8;
  15025. };
  15026. ;
  15027. Engine.prototype.createQuery = function () {
  15028. return this._gl.createQuery();
  15029. };
  15030. Engine.prototype.deleteQuery = function (query) {
  15031. this._gl.deleteQuery(query);
  15032. return this;
  15033. };
  15034. Engine.prototype.isQueryResultAvailable = function (query) {
  15035. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15036. };
  15037. Engine.prototype.getQueryResult = function (query) {
  15038. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15039. };
  15040. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15041. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15042. this._gl.beginQuery(glAlgorithm, query);
  15043. return this;
  15044. };
  15045. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15046. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15047. this._gl.endQuery(glAlgorithm);
  15048. return this;
  15049. };
  15050. /* Time queries */
  15051. Engine.prototype._createTimeQuery = function () {
  15052. var timerQuery = this._caps.timerQuery;
  15053. if (timerQuery.createQueryEXT) {
  15054. return timerQuery.createQueryEXT();
  15055. }
  15056. return this.createQuery();
  15057. };
  15058. Engine.prototype._deleteTimeQuery = function (query) {
  15059. var timerQuery = this._caps.timerQuery;
  15060. if (timerQuery.deleteQueryEXT) {
  15061. timerQuery.deleteQueryEXT(query);
  15062. return;
  15063. }
  15064. this.deleteQuery(query);
  15065. };
  15066. Engine.prototype._getTimeQueryResult = function (query) {
  15067. var timerQuery = this._caps.timerQuery;
  15068. if (timerQuery.getQueryObjectEXT) {
  15069. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15070. }
  15071. return this.getQueryResult(query);
  15072. };
  15073. Engine.prototype._getTimeQueryAvailability = function (query) {
  15074. var timerQuery = this._caps.timerQuery;
  15075. if (timerQuery.getQueryObjectEXT) {
  15076. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15077. }
  15078. return this.isQueryResultAvailable(query);
  15079. };
  15080. Engine.prototype.startTimeQuery = function () {
  15081. var timerQuery = this._caps.timerQuery;
  15082. if (!timerQuery) {
  15083. return null;
  15084. }
  15085. var token = new BABYLON._TimeToken();
  15086. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15087. if (this._caps.canUseTimestampForTimerQuery) {
  15088. token._startTimeQuery = this._createTimeQuery();
  15089. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15090. }
  15091. else {
  15092. if (this._currentNonTimestampToken) {
  15093. return this._currentNonTimestampToken;
  15094. }
  15095. token._timeElapsedQuery = this._createTimeQuery();
  15096. if (timerQuery.beginQueryEXT) {
  15097. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15098. }
  15099. else {
  15100. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15101. }
  15102. this._currentNonTimestampToken = token;
  15103. }
  15104. return token;
  15105. };
  15106. Engine.prototype.endTimeQuery = function (token) {
  15107. var timerQuery = this._caps.timerQuery;
  15108. if (!timerQuery || !token) {
  15109. return -1;
  15110. }
  15111. if (this._caps.canUseTimestampForTimerQuery) {
  15112. if (!token._startTimeQuery) {
  15113. return -1;
  15114. }
  15115. if (!token._endTimeQuery) {
  15116. token._endTimeQuery = this._createTimeQuery();
  15117. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15118. }
  15119. }
  15120. else if (!token._timeElapsedQueryEnded) {
  15121. if (!token._timeElapsedQuery) {
  15122. return -1;
  15123. }
  15124. if (timerQuery.endQueryEXT) {
  15125. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15126. }
  15127. else {
  15128. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15129. }
  15130. token._timeElapsedQueryEnded = true;
  15131. }
  15132. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15133. var available = false;
  15134. if (token._endTimeQuery) {
  15135. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15136. }
  15137. else if (token._timeElapsedQuery) {
  15138. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15139. }
  15140. if (available && !disjoint) {
  15141. var result = 0;
  15142. if (this._caps.canUseTimestampForTimerQuery) {
  15143. if (!token._startTimeQuery || !token._endTimeQuery) {
  15144. return -1;
  15145. }
  15146. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15147. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15148. result = timeEnd - timeStart;
  15149. this._deleteTimeQuery(token._startTimeQuery);
  15150. this._deleteTimeQuery(token._endTimeQuery);
  15151. token._startTimeQuery = null;
  15152. token._endTimeQuery = null;
  15153. }
  15154. else {
  15155. if (!token._timeElapsedQuery) {
  15156. return -1;
  15157. }
  15158. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15159. this._deleteTimeQuery(token._timeElapsedQuery);
  15160. token._timeElapsedQuery = null;
  15161. token._timeElapsedQueryEnded = false;
  15162. this._currentNonTimestampToken = null;
  15163. }
  15164. return result;
  15165. }
  15166. return -1;
  15167. };
  15168. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15169. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15170. };
  15171. // Transform feedback
  15172. Engine.prototype.createTransformFeedback = function () {
  15173. return this._gl.createTransformFeedback();
  15174. };
  15175. Engine.prototype.deleteTransformFeedback = function (value) {
  15176. this._gl.deleteTransformFeedback(value);
  15177. };
  15178. Engine.prototype.bindTransformFeedback = function (value) {
  15179. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15180. };
  15181. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15182. if (usePoints === void 0) { usePoints = true; }
  15183. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15184. };
  15185. Engine.prototype.endTransformFeedback = function () {
  15186. this._gl.endTransformFeedback();
  15187. };
  15188. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15189. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15190. };
  15191. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15192. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15193. };
  15194. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15195. var _this = this;
  15196. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15197. this._activeRequests.push(request);
  15198. request.onCompleteObservable.add(function (request) {
  15199. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15200. });
  15201. return request;
  15202. };
  15203. /** @ignore */
  15204. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15205. var _this = this;
  15206. return new Promise(function (resolve, reject) {
  15207. _this._loadFile(url, function (data) {
  15208. resolve(data);
  15209. }, undefined, database, useArrayBuffer, function (request, exception) {
  15210. reject(exception);
  15211. });
  15212. });
  15213. };
  15214. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15215. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15216. var onload = function (data) {
  15217. loadedFiles[index] = data;
  15218. loadedFiles._internalCount++;
  15219. if (loadedFiles._internalCount === 6) {
  15220. onfinish(loadedFiles);
  15221. }
  15222. };
  15223. var onerror = function (request, exception) {
  15224. if (onErrorCallBack && request) {
  15225. onErrorCallBack(request.status + " " + request.statusText, exception);
  15226. }
  15227. };
  15228. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15229. };
  15230. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15231. if (onError === void 0) { onError = null; }
  15232. var loadedFiles = [];
  15233. loadedFiles._internalCount = 0;
  15234. for (var index = 0; index < 6; index++) {
  15235. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15236. }
  15237. };
  15238. // Statics
  15239. Engine.isSupported = function () {
  15240. try {
  15241. var tempcanvas = document.createElement("canvas");
  15242. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15243. return gl != null && !!window.WebGLRenderingContext;
  15244. }
  15245. catch (e) {
  15246. return false;
  15247. }
  15248. };
  15249. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15250. Engine.ExceptionList = [
  15251. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15252. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15253. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15254. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15255. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15256. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15257. ];
  15258. Engine.Instances = new Array();
  15259. // Const statics
  15260. Engine._ALPHA_DISABLE = 0;
  15261. Engine._ALPHA_ADD = 1;
  15262. Engine._ALPHA_COMBINE = 2;
  15263. Engine._ALPHA_SUBTRACT = 3;
  15264. Engine._ALPHA_MULTIPLY = 4;
  15265. Engine._ALPHA_MAXIMIZED = 5;
  15266. Engine._ALPHA_ONEONE = 6;
  15267. Engine._ALPHA_PREMULTIPLIED = 7;
  15268. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15269. Engine._ALPHA_INTERPOLATE = 9;
  15270. Engine._ALPHA_SCREENMODE = 10;
  15271. Engine._DELAYLOADSTATE_NONE = 0;
  15272. Engine._DELAYLOADSTATE_LOADED = 1;
  15273. Engine._DELAYLOADSTATE_LOADING = 2;
  15274. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15275. Engine._TEXTUREFORMAT_ALPHA = 0;
  15276. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15277. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15278. Engine._TEXTUREFORMAT_RGB = 4;
  15279. Engine._TEXTUREFORMAT_RGBA = 5;
  15280. Engine._TEXTUREFORMAT_R32F = 6;
  15281. Engine._TEXTUREFORMAT_RG32F = 7;
  15282. Engine._TEXTUREFORMAT_RGB32F = 8;
  15283. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15284. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15285. Engine._TEXTURETYPE_FLOAT = 1;
  15286. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15287. // Depht or Stencil test Constants.
  15288. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15289. Engine._ALWAYS = 0x0207; // 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.
  15290. Engine._LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
  15291. Engine._EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
  15292. Engine._LEQUAL = 0x0203; // 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.
  15293. Engine._GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
  15294. Engine._GEQUAL = 0x0206; // 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.
  15295. Engine._NOTEQUAL = 0x0205; // 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.
  15296. // Stencil Actions Constants.
  15297. Engine._KEEP = 0x1E00;
  15298. Engine._REPLACE = 0x1E01;
  15299. Engine._INCR = 0x1E02;
  15300. Engine._DECR = 0x1E03;
  15301. Engine._INVERT = 0x150A;
  15302. Engine._INCR_WRAP = 0x8507;
  15303. Engine._DECR_WRAP = 0x8508;
  15304. // Texture rescaling mode
  15305. Engine._SCALEMODE_FLOOR = 1;
  15306. Engine._SCALEMODE_NEAREST = 2;
  15307. Engine._SCALEMODE_CEILING = 3;
  15308. // Updatable statics so stick with vars here
  15309. Engine.CollisionsEpsilon = 0.001;
  15310. Engine.CodeRepository = "src/";
  15311. Engine.ShadersRepository = "src/Shaders/";
  15312. return Engine;
  15313. }());
  15314. BABYLON.Engine = Engine;
  15315. })(BABYLON || (BABYLON = {}));
  15316. //# sourceMappingURL=babylon.engine.js.map
  15317. var BABYLON;
  15318. (function (BABYLON) {
  15319. /**
  15320. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15321. */
  15322. var Node = /** @class */ (function () {
  15323. /**
  15324. * Creates a new Node
  15325. * @param {string} name - the name and id to be given to this node
  15326. * @param {BABYLON.Scene} the scene this node will be added to
  15327. */
  15328. function Node(name, scene) {
  15329. if (scene === void 0) { scene = null; }
  15330. /**
  15331. * Gets or sets a string used to store user defined state for the node
  15332. */
  15333. this.state = "";
  15334. /**
  15335. * Gets or sets an object used to store user defined information for the node
  15336. */
  15337. this.metadata = null;
  15338. /**
  15339. * Gets or sets a boolean used to define if the node must be serialized
  15340. */
  15341. this.doNotSerialize = false;
  15342. /** @ignore */
  15343. this._isDisposed = false;
  15344. /**
  15345. * Gets a list of {BABYLON.Animation} associated with the node
  15346. */
  15347. this.animations = new Array();
  15348. this._ranges = {};
  15349. this._isEnabled = true;
  15350. this._isReady = true;
  15351. /** @ignore */
  15352. this._currentRenderId = -1;
  15353. this._parentRenderId = -1;
  15354. /**
  15355. * An event triggered when the mesh is disposed
  15356. * @type {BABYLON.Observable}
  15357. */
  15358. this.onDisposeObservable = new BABYLON.Observable();
  15359. // Behaviors
  15360. this._behaviors = new Array();
  15361. this.name = name;
  15362. this.id = name;
  15363. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15364. this.uniqueId = this._scene.getUniqueId();
  15365. this._initCache();
  15366. }
  15367. /**
  15368. * Gets a boolean indicating if the node has been disposed
  15369. * @returns true if the node was disposed
  15370. */
  15371. Node.prototype.isDisposed = function () {
  15372. return this._isDisposed;
  15373. };
  15374. Object.defineProperty(Node.prototype, "parent", {
  15375. get: function () {
  15376. return this._parentNode;
  15377. },
  15378. /**
  15379. * Gets or sets the parent of the node
  15380. */
  15381. set: function (parent) {
  15382. if (this._parentNode === parent) {
  15383. return;
  15384. }
  15385. // Remove self from list of children of parent
  15386. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15387. var index = this._parentNode._children.indexOf(this);
  15388. if (index !== -1) {
  15389. this._parentNode._children.splice(index, 1);
  15390. }
  15391. }
  15392. // Store new parent
  15393. this._parentNode = parent;
  15394. // Add as child to new parent
  15395. if (this._parentNode) {
  15396. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15397. this._parentNode._children = new Array();
  15398. }
  15399. this._parentNode._children.push(this);
  15400. }
  15401. },
  15402. enumerable: true,
  15403. configurable: true
  15404. });
  15405. /**
  15406. * Gets a string idenfifying the name of the class
  15407. * @returns "Node" string
  15408. */
  15409. Node.prototype.getClassName = function () {
  15410. return "Node";
  15411. };
  15412. Object.defineProperty(Node.prototype, "onDispose", {
  15413. /**
  15414. * Sets a callback that will be raised when the node will be disposed
  15415. */
  15416. set: function (callback) {
  15417. if (this._onDisposeObserver) {
  15418. this.onDisposeObservable.remove(this._onDisposeObserver);
  15419. }
  15420. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15421. },
  15422. enumerable: true,
  15423. configurable: true
  15424. });
  15425. /**
  15426. * Gets the scene of the node
  15427. * @returns a {BABYLON.Scene}
  15428. */
  15429. Node.prototype.getScene = function () {
  15430. return this._scene;
  15431. };
  15432. /**
  15433. * Gets the engine of the node
  15434. * @returns a {BABYLON.Engine}
  15435. */
  15436. Node.prototype.getEngine = function () {
  15437. return this._scene.getEngine();
  15438. };
  15439. /**
  15440. * Attach a behavior to the node
  15441. * @see http://doc.babylonjs.com/features/behaviour
  15442. * @param behavior defines the behavior to attach
  15443. * @returns the current Node
  15444. */
  15445. Node.prototype.addBehavior = function (behavior) {
  15446. var _this = this;
  15447. var index = this._behaviors.indexOf(behavior);
  15448. if (index !== -1) {
  15449. return this;
  15450. }
  15451. behavior.init();
  15452. if (this._scene.isLoading) {
  15453. // We defer the attach when the scene will be loaded
  15454. var observer = this._scene.onDataLoadedObservable.add(function () {
  15455. behavior.attach(_this);
  15456. setTimeout(function () {
  15457. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15458. _this._scene.onDataLoadedObservable.remove(observer);
  15459. }, 0);
  15460. });
  15461. }
  15462. else {
  15463. behavior.attach(this);
  15464. }
  15465. this._behaviors.push(behavior);
  15466. return this;
  15467. };
  15468. /**
  15469. * Remove an attached behavior
  15470. * @see http://doc.babylonjs.com/features/behaviour
  15471. * @param behavior defines the behavior to attach
  15472. * @returns the current Node
  15473. */
  15474. Node.prototype.removeBehavior = function (behavior) {
  15475. var index = this._behaviors.indexOf(behavior);
  15476. if (index === -1) {
  15477. return this;
  15478. }
  15479. this._behaviors[index].detach();
  15480. this._behaviors.splice(index, 1);
  15481. return this;
  15482. };
  15483. Object.defineProperty(Node.prototype, "behaviors", {
  15484. /**
  15485. * Gets the list of attached behaviors
  15486. * @see http://doc.babylonjs.com/features/behaviour
  15487. */
  15488. get: function () {
  15489. return this._behaviors;
  15490. },
  15491. enumerable: true,
  15492. configurable: true
  15493. });
  15494. /**
  15495. * Gets an attached behavior by name
  15496. * @param name defines the name of the behavior to look for
  15497. * @see http://doc.babylonjs.com/features/behaviour
  15498. * @returns null if behavior was not found else the requested behavior
  15499. */
  15500. Node.prototype.getBehaviorByName = function (name) {
  15501. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15502. var behavior = _a[_i];
  15503. if (behavior.name === name) {
  15504. return behavior;
  15505. }
  15506. }
  15507. return null;
  15508. };
  15509. /**
  15510. * Returns the world matrix of the node
  15511. * @returns a matrix containing the node's world matrix
  15512. */
  15513. Node.prototype.getWorldMatrix = function () {
  15514. return BABYLON.Matrix.Identity();
  15515. };
  15516. // override it in derived class if you add new variables to the cache
  15517. // and call the parent class method
  15518. /** @ignore */
  15519. Node.prototype._initCache = function () {
  15520. this._cache = {};
  15521. this._cache.parent = undefined;
  15522. };
  15523. /** @ignore */
  15524. Node.prototype.updateCache = function (force) {
  15525. if (!force && this.isSynchronized())
  15526. return;
  15527. this._cache.parent = this.parent;
  15528. this._updateCache();
  15529. };
  15530. // override it in derived class if you add new variables to the cache
  15531. // and call the parent class method if !ignoreParentClass
  15532. /** @ignore */
  15533. Node.prototype._updateCache = function (ignoreParentClass) {
  15534. };
  15535. // override it in derived class if you add new variables to the cache
  15536. /** @ignore */
  15537. Node.prototype._isSynchronized = function () {
  15538. return true;
  15539. };
  15540. /** @ignore */
  15541. Node.prototype._markSyncedWithParent = function () {
  15542. if (this.parent) {
  15543. this._parentRenderId = this.parent._currentRenderId;
  15544. }
  15545. };
  15546. /** @ignore */
  15547. Node.prototype.isSynchronizedWithParent = function () {
  15548. if (!this.parent) {
  15549. return true;
  15550. }
  15551. if (this._parentRenderId !== this.parent._currentRenderId) {
  15552. return false;
  15553. }
  15554. return this.parent.isSynchronized();
  15555. };
  15556. /** @ignore */
  15557. Node.prototype.isSynchronized = function (updateCache) {
  15558. var check = this.hasNewParent();
  15559. check = check || !this.isSynchronizedWithParent();
  15560. check = check || !this._isSynchronized();
  15561. if (updateCache)
  15562. this.updateCache(true);
  15563. return !check;
  15564. };
  15565. /** @ignore */
  15566. Node.prototype.hasNewParent = function (update) {
  15567. if (this._cache.parent === this.parent)
  15568. return false;
  15569. if (update)
  15570. this._cache.parent = this.parent;
  15571. return true;
  15572. };
  15573. /**
  15574. * Is this node ready to be used/rendered
  15575. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15576. * @return true if the node is ready
  15577. */
  15578. Node.prototype.isReady = function (completeCheck) {
  15579. if (completeCheck === void 0) { completeCheck = false; }
  15580. return this._isReady;
  15581. };
  15582. /**
  15583. * Is this node enabled?
  15584. * 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
  15585. * @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
  15586. * @return whether this node (and its parent) is enabled
  15587. * @see setEnabled
  15588. */
  15589. Node.prototype.isEnabled = function (checkAncestors) {
  15590. if (checkAncestors === void 0) { checkAncestors = true; }
  15591. if (checkAncestors === false) {
  15592. return this._isEnabled;
  15593. }
  15594. if (this._isEnabled === false) {
  15595. return false;
  15596. }
  15597. if (this.parent !== undefined && this.parent !== null) {
  15598. return this.parent.isEnabled(checkAncestors);
  15599. }
  15600. return true;
  15601. };
  15602. /**
  15603. * Set the enabled state of this node
  15604. * @param value defines the new enabled state
  15605. * @see isEnabled
  15606. */
  15607. Node.prototype.setEnabled = function (value) {
  15608. this._isEnabled = value;
  15609. };
  15610. /**
  15611. * Is this node a descendant of the given node?
  15612. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15613. * @param ancestor defines the parent node to inspect
  15614. * @see parent
  15615. * @returns a boolean indicating if this node is a descendant of the given node
  15616. */
  15617. Node.prototype.isDescendantOf = function (ancestor) {
  15618. if (this.parent) {
  15619. if (this.parent === ancestor) {
  15620. return true;
  15621. }
  15622. return this.parent.isDescendantOf(ancestor);
  15623. }
  15624. return false;
  15625. };
  15626. /** @ignore */
  15627. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15628. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15629. if (!this._children) {
  15630. return;
  15631. }
  15632. for (var index = 0; index < this._children.length; index++) {
  15633. var item = this._children[index];
  15634. if (!predicate || predicate(item)) {
  15635. results.push(item);
  15636. }
  15637. if (!directDescendantsOnly) {
  15638. item._getDescendants(results, false, predicate);
  15639. }
  15640. }
  15641. };
  15642. /**
  15643. * Will return all nodes that have this node as ascendant
  15644. * @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
  15645. * @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
  15646. * @return all children nodes of all types
  15647. */
  15648. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15649. var results = new Array();
  15650. this._getDescendants(results, directDescendantsOnly, predicate);
  15651. return results;
  15652. };
  15653. /**
  15654. * Get all child-meshes of this node
  15655. * @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
  15656. * @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
  15657. * @returns an array of {BABYLON.AbstractMesh}
  15658. */
  15659. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15660. var results = [];
  15661. this._getDescendants(results, directDescendantsOnly, function (node) {
  15662. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15663. });
  15664. return results;
  15665. };
  15666. /**
  15667. * Get all child-transformNodes of this node
  15668. * @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
  15669. * @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
  15670. * @returns an array of {BABYLON.TransformNode}
  15671. */
  15672. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15673. var results = [];
  15674. this._getDescendants(results, directDescendantsOnly, function (node) {
  15675. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15676. });
  15677. return results;
  15678. };
  15679. /**
  15680. * Get all direct children of this node
  15681. * @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
  15682. * @returns an array of {BABYLON.Node}
  15683. */
  15684. Node.prototype.getChildren = function (predicate) {
  15685. return this.getDescendants(true, predicate);
  15686. };
  15687. /** @ignore */
  15688. Node.prototype._setReady = function (state) {
  15689. if (state === this._isReady) {
  15690. return;
  15691. }
  15692. if (!state) {
  15693. this._isReady = false;
  15694. return;
  15695. }
  15696. this._isReady = true;
  15697. if (this.onReady) {
  15698. this.onReady(this);
  15699. }
  15700. };
  15701. /**
  15702. * Get an animation by name
  15703. * @param name defines the name of the animation to look for
  15704. * @returns null if not found else the requested animation
  15705. */
  15706. Node.prototype.getAnimationByName = function (name) {
  15707. for (var i = 0; i < this.animations.length; i++) {
  15708. var animation = this.animations[i];
  15709. if (animation.name === name) {
  15710. return animation;
  15711. }
  15712. }
  15713. return null;
  15714. };
  15715. /**
  15716. * Creates an animation range for this node
  15717. * @param name defines the name of the range
  15718. * @param from defines the starting key
  15719. * @param to defines the end key
  15720. */
  15721. Node.prototype.createAnimationRange = function (name, from, to) {
  15722. // check name not already in use
  15723. if (!this._ranges[name]) {
  15724. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  15725. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15726. if (this.animations[i]) {
  15727. this.animations[i].createRange(name, from, to);
  15728. }
  15729. }
  15730. }
  15731. };
  15732. /**
  15733. * Delete a specific animation range
  15734. * @param name defines the name of the range to delete
  15735. * @param deleteFrames defines if animation frames from the range must be deleted as well
  15736. */
  15737. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  15738. if (deleteFrames === void 0) { deleteFrames = true; }
  15739. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15740. if (this.animations[i]) {
  15741. this.animations[i].deleteRange(name, deleteFrames);
  15742. }
  15743. }
  15744. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  15745. };
  15746. /**
  15747. * Get an animation range by name
  15748. * @param name defines the name of the animation range to look for
  15749. * @returns null if not found else the requested animation range
  15750. */
  15751. Node.prototype.getAnimationRange = function (name) {
  15752. return this._ranges[name];
  15753. };
  15754. /**
  15755. * Will start the animation sequence
  15756. * @param name defines the range frames for animation sequence
  15757. * @param loop defines if the animation should loop (false by default)
  15758. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  15759. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  15760. * @returns the object created for this animation. If range does not exist, it will return null
  15761. */
  15762. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  15763. var range = this.getAnimationRange(name);
  15764. if (!range) {
  15765. return null;
  15766. }
  15767. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  15768. };
  15769. /**
  15770. * Serialize animation ranges into a JSON compatible object
  15771. * @returns serialization object
  15772. */
  15773. Node.prototype.serializeAnimationRanges = function () {
  15774. var serializationRanges = [];
  15775. for (var name in this._ranges) {
  15776. var localRange = this._ranges[name];
  15777. if (!localRange) {
  15778. continue;
  15779. }
  15780. var range = {};
  15781. range.name = name;
  15782. range.from = localRange.from;
  15783. range.to = localRange.to;
  15784. serializationRanges.push(range);
  15785. }
  15786. return serializationRanges;
  15787. };
  15788. /**
  15789. * Computes the world matrix of the node
  15790. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  15791. * @returns the world matrix
  15792. */
  15793. Node.prototype.computeWorldMatrix = function (force) {
  15794. return BABYLON.Matrix.Identity();
  15795. };
  15796. /**
  15797. * Releases all associated resources
  15798. */
  15799. Node.prototype.dispose = function () {
  15800. this.parent = null;
  15801. // Callback
  15802. this.onDisposeObservable.notifyObservers(this);
  15803. this.onDisposeObservable.clear();
  15804. // Behaviors
  15805. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15806. var behavior = _a[_i];
  15807. behavior.detach();
  15808. }
  15809. this._behaviors = [];
  15810. this._isDisposed = true;
  15811. };
  15812. /**
  15813. * Parse animation range data from a serialization object and store them into a given node
  15814. * @param node defines where to store the animation ranges
  15815. * @param parsedNode defines the serialization object to read data from
  15816. * @param scene defines the hosting scene
  15817. */
  15818. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  15819. if (parsedNode.ranges) {
  15820. for (var index = 0; index < parsedNode.ranges.length; index++) {
  15821. var data = parsedNode.ranges[index];
  15822. node.createAnimationRange(data.name, data.from, data.to);
  15823. }
  15824. }
  15825. };
  15826. __decorate([
  15827. BABYLON.serialize()
  15828. ], Node.prototype, "name", void 0);
  15829. __decorate([
  15830. BABYLON.serialize()
  15831. ], Node.prototype, "id", void 0);
  15832. __decorate([
  15833. BABYLON.serialize()
  15834. ], Node.prototype, "uniqueId", void 0);
  15835. __decorate([
  15836. BABYLON.serialize()
  15837. ], Node.prototype, "state", void 0);
  15838. __decorate([
  15839. BABYLON.serialize()
  15840. ], Node.prototype, "metadata", void 0);
  15841. return Node;
  15842. }());
  15843. BABYLON.Node = Node;
  15844. })(BABYLON || (BABYLON = {}));
  15845. //# sourceMappingURL=babylon.node.js.map
  15846. var BABYLON;
  15847. (function (BABYLON) {
  15848. var BoundingSphere = /** @class */ (function () {
  15849. function BoundingSphere(minimum, maximum) {
  15850. this.minimum = minimum;
  15851. this.maximum = maximum;
  15852. this._tempRadiusVector = BABYLON.Vector3.Zero();
  15853. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  15854. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  15855. this.radius = distance * 0.5;
  15856. this.centerWorld = BABYLON.Vector3.Zero();
  15857. this._update(BABYLON.Matrix.Identity());
  15858. }
  15859. // Methods
  15860. BoundingSphere.prototype._update = function (world) {
  15861. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  15862. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  15863. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  15864. };
  15865. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  15866. for (var i = 0; i < 6; i++) {
  15867. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  15868. return false;
  15869. }
  15870. return true;
  15871. };
  15872. BoundingSphere.prototype.intersectsPoint = function (point) {
  15873. var x = this.centerWorld.x - point.x;
  15874. var y = this.centerWorld.y - point.y;
  15875. var z = this.centerWorld.z - point.z;
  15876. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15877. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  15878. return false;
  15879. return true;
  15880. };
  15881. // Statics
  15882. BoundingSphere.Intersects = function (sphere0, sphere1) {
  15883. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  15884. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  15885. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  15886. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15887. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  15888. return false;
  15889. return true;
  15890. };
  15891. return BoundingSphere;
  15892. }());
  15893. BABYLON.BoundingSphere = BoundingSphere;
  15894. })(BABYLON || (BABYLON = {}));
  15895. //# sourceMappingURL=babylon.boundingSphere.js.map
  15896. var BABYLON;
  15897. (function (BABYLON) {
  15898. var BoundingBox = /** @class */ (function () {
  15899. function BoundingBox(minimum, maximum) {
  15900. this.minimum = minimum;
  15901. this.maximum = maximum;
  15902. this.vectors = new Array();
  15903. this.vectorsWorld = new Array();
  15904. // Bounding vectors
  15905. this.vectors.push(this.minimum.clone());
  15906. this.vectors.push(this.maximum.clone());
  15907. this.vectors.push(this.minimum.clone());
  15908. this.vectors[2].x = this.maximum.x;
  15909. this.vectors.push(this.minimum.clone());
  15910. this.vectors[3].y = this.maximum.y;
  15911. this.vectors.push(this.minimum.clone());
  15912. this.vectors[4].z = this.maximum.z;
  15913. this.vectors.push(this.maximum.clone());
  15914. this.vectors[5].z = this.minimum.z;
  15915. this.vectors.push(this.maximum.clone());
  15916. this.vectors[6].x = this.minimum.x;
  15917. this.vectors.push(this.maximum.clone());
  15918. this.vectors[7].y = this.minimum.y;
  15919. // OBB
  15920. this.center = this.maximum.add(this.minimum).scale(0.5);
  15921. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  15922. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  15923. // World
  15924. for (var index = 0; index < this.vectors.length; index++) {
  15925. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  15926. }
  15927. this.minimumWorld = BABYLON.Vector3.Zero();
  15928. this.maximumWorld = BABYLON.Vector3.Zero();
  15929. this.centerWorld = BABYLON.Vector3.Zero();
  15930. this.extendSizeWorld = BABYLON.Vector3.Zero();
  15931. this._update(BABYLON.Matrix.Identity());
  15932. }
  15933. // Methods
  15934. BoundingBox.prototype.getWorldMatrix = function () {
  15935. return this._worldMatrix;
  15936. };
  15937. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  15938. this._worldMatrix.copyFrom(matrix);
  15939. return this;
  15940. };
  15941. BoundingBox.prototype._update = function (world) {
  15942. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  15943. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  15944. for (var index = 0; index < this.vectors.length; index++) {
  15945. var v = this.vectorsWorld[index];
  15946. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  15947. if (v.x < this.minimumWorld.x)
  15948. this.minimumWorld.x = v.x;
  15949. if (v.y < this.minimumWorld.y)
  15950. this.minimumWorld.y = v.y;
  15951. if (v.z < this.minimumWorld.z)
  15952. this.minimumWorld.z = v.z;
  15953. if (v.x > this.maximumWorld.x)
  15954. this.maximumWorld.x = v.x;
  15955. if (v.y > this.maximumWorld.y)
  15956. this.maximumWorld.y = v.y;
  15957. if (v.z > this.maximumWorld.z)
  15958. this.maximumWorld.z = v.z;
  15959. }
  15960. // Extend
  15961. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  15962. this.extendSizeWorld.scaleInPlace(0.5);
  15963. // OBB
  15964. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  15965. this.centerWorld.scaleInPlace(0.5);
  15966. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  15967. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  15968. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  15969. this._worldMatrix = world;
  15970. };
  15971. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  15972. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  15973. };
  15974. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15975. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  15976. };
  15977. BoundingBox.prototype.intersectsPoint = function (point) {
  15978. var delta = -BABYLON.Epsilon;
  15979. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  15980. return false;
  15981. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  15982. return false;
  15983. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  15984. return false;
  15985. return true;
  15986. };
  15987. BoundingBox.prototype.intersectsSphere = function (sphere) {
  15988. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  15989. };
  15990. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  15991. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  15992. return false;
  15993. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  15994. return false;
  15995. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  15996. return false;
  15997. return true;
  15998. };
  15999. // Statics
  16000. BoundingBox.Intersects = function (box0, box1) {
  16001. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16002. return false;
  16003. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16004. return false;
  16005. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16006. return false;
  16007. return true;
  16008. };
  16009. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16010. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16011. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16012. return (num <= (sphereRadius * sphereRadius));
  16013. };
  16014. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16015. for (var p = 0; p < 6; p++) {
  16016. for (var i = 0; i < 8; i++) {
  16017. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16018. return false;
  16019. }
  16020. }
  16021. }
  16022. return true;
  16023. };
  16024. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16025. for (var p = 0; p < 6; p++) {
  16026. var inCount = 8;
  16027. for (var i = 0; i < 8; i++) {
  16028. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16029. --inCount;
  16030. }
  16031. else {
  16032. break;
  16033. }
  16034. }
  16035. if (inCount === 0)
  16036. return false;
  16037. }
  16038. return true;
  16039. };
  16040. return BoundingBox;
  16041. }());
  16042. BABYLON.BoundingBox = BoundingBox;
  16043. })(BABYLON || (BABYLON = {}));
  16044. //# sourceMappingURL=babylon.boundingBox.js.map
  16045. var BABYLON;
  16046. (function (BABYLON) {
  16047. var computeBoxExtents = function (axis, box) {
  16048. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16049. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16050. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16051. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16052. var r = r0 + r1 + r2;
  16053. return {
  16054. min: p - r,
  16055. max: p + r
  16056. };
  16057. };
  16058. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16059. var axisOverlap = function (axis, box0, box1) {
  16060. var result0 = computeBoxExtents(axis, box0);
  16061. var result1 = computeBoxExtents(axis, box1);
  16062. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16063. };
  16064. var BoundingInfo = /** @class */ (function () {
  16065. function BoundingInfo(minimum, maximum) {
  16066. this.minimum = minimum;
  16067. this.maximum = maximum;
  16068. this._isLocked = false;
  16069. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16070. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16071. }
  16072. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16073. get: function () {
  16074. return this._isLocked;
  16075. },
  16076. set: function (value) {
  16077. this._isLocked = value;
  16078. },
  16079. enumerable: true,
  16080. configurable: true
  16081. });
  16082. // Methods
  16083. BoundingInfo.prototype.update = function (world) {
  16084. if (this._isLocked) {
  16085. return;
  16086. }
  16087. this.boundingBox._update(world);
  16088. this.boundingSphere._update(world);
  16089. };
  16090. /**
  16091. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16092. * @param center New center of the bounding info
  16093. * @param extend New extend of the bounding info
  16094. */
  16095. BoundingInfo.prototype.centerOn = function (center, extend) {
  16096. this.minimum = center.subtract(extend);
  16097. this.maximum = center.add(extend);
  16098. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16099. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16100. return this;
  16101. };
  16102. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16103. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16104. return false;
  16105. return this.boundingBox.isInFrustum(frustumPlanes);
  16106. };
  16107. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16108. /**
  16109. * Gets the world distance between the min and max points of the bounding box
  16110. */
  16111. get: function () {
  16112. var boundingBox = this.boundingBox;
  16113. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16114. return size.length();
  16115. },
  16116. enumerable: true,
  16117. configurable: true
  16118. });
  16119. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16120. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16121. };
  16122. BoundingInfo.prototype._checkCollision = function (collider) {
  16123. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16124. };
  16125. BoundingInfo.prototype.intersectsPoint = function (point) {
  16126. if (!this.boundingSphere.centerWorld) {
  16127. return false;
  16128. }
  16129. if (!this.boundingSphere.intersectsPoint(point)) {
  16130. return false;
  16131. }
  16132. if (!this.boundingBox.intersectsPoint(point)) {
  16133. return false;
  16134. }
  16135. return true;
  16136. };
  16137. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16138. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16139. return false;
  16140. }
  16141. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16142. return false;
  16143. }
  16144. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16145. return false;
  16146. }
  16147. if (!precise) {
  16148. return true;
  16149. }
  16150. var box0 = this.boundingBox;
  16151. var box1 = boundingInfo.boundingBox;
  16152. if (!axisOverlap(box0.directions[0], box0, box1))
  16153. return false;
  16154. if (!axisOverlap(box0.directions[1], box0, box1))
  16155. return false;
  16156. if (!axisOverlap(box0.directions[2], box0, box1))
  16157. return false;
  16158. if (!axisOverlap(box1.directions[0], box0, box1))
  16159. return false;
  16160. if (!axisOverlap(box1.directions[1], box0, box1))
  16161. return false;
  16162. if (!axisOverlap(box1.directions[2], box0, box1))
  16163. return false;
  16164. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16165. return false;
  16166. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16167. return false;
  16168. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16169. return false;
  16170. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16171. return false;
  16172. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16173. return false;
  16174. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16175. return false;
  16176. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16177. return false;
  16178. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16179. return false;
  16180. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16181. return false;
  16182. return true;
  16183. };
  16184. return BoundingInfo;
  16185. }());
  16186. BABYLON.BoundingInfo = BoundingInfo;
  16187. })(BABYLON || (BABYLON = {}));
  16188. //# sourceMappingURL=babylon.boundingInfo.js.map
  16189. var BABYLON;
  16190. (function (BABYLON) {
  16191. var TransformNode = /** @class */ (function (_super) {
  16192. __extends(TransformNode, _super);
  16193. function TransformNode(name, scene, isPure) {
  16194. if (scene === void 0) { scene = null; }
  16195. if (isPure === void 0) { isPure = true; }
  16196. var _this = _super.call(this, name, scene) || this;
  16197. // Properties
  16198. _this._rotation = BABYLON.Vector3.Zero();
  16199. _this._scaling = BABYLON.Vector3.One();
  16200. _this._isDirty = false;
  16201. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  16202. _this.scalingDeterminant = 1;
  16203. _this.infiniteDistance = false;
  16204. _this.position = BABYLON.Vector3.Zero();
  16205. _this._localWorld = BABYLON.Matrix.Zero();
  16206. _this._worldMatrix = BABYLON.Matrix.Zero();
  16207. _this._worldMatrixDeterminant = 0;
  16208. _this._absolutePosition = BABYLON.Vector3.Zero();
  16209. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16210. _this._postMultiplyPivotMatrix = false;
  16211. _this._isWorldMatrixFrozen = false;
  16212. /**
  16213. * An event triggered after the world matrix is updated
  16214. * @type {BABYLON.Observable}
  16215. */
  16216. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16217. _this._nonUniformScaling = false;
  16218. if (isPure) {
  16219. _this.getScene().addTransformNode(_this);
  16220. }
  16221. return _this;
  16222. }
  16223. Object.defineProperty(TransformNode.prototype, "rotation", {
  16224. /**
  16225. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16226. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16227. * Default : (0.0, 0.0, 0.0)
  16228. */
  16229. get: function () {
  16230. return this._rotation;
  16231. },
  16232. set: function (newRotation) {
  16233. this._rotation = newRotation;
  16234. },
  16235. enumerable: true,
  16236. configurable: true
  16237. });
  16238. Object.defineProperty(TransformNode.prototype, "scaling", {
  16239. /**
  16240. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16241. * Default : (1.0, 1.0, 1.0)
  16242. */
  16243. get: function () {
  16244. return this._scaling;
  16245. },
  16246. /**
  16247. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16248. * Default : (1.0, 1.0, 1.0)
  16249. */
  16250. set: function (newScaling) {
  16251. this._scaling = newScaling;
  16252. },
  16253. enumerable: true,
  16254. configurable: true
  16255. });
  16256. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16257. /**
  16258. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16259. * It's null by default.
  16260. * 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)
  16261. */
  16262. get: function () {
  16263. return this._rotationQuaternion;
  16264. },
  16265. set: function (quaternion) {
  16266. this._rotationQuaternion = quaternion;
  16267. //reset the rotation vector.
  16268. if (quaternion && this.rotation.length()) {
  16269. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16270. }
  16271. },
  16272. enumerable: true,
  16273. configurable: true
  16274. });
  16275. /**
  16276. * Returns the latest update of the World matrix
  16277. * Returns a Matrix.
  16278. */
  16279. TransformNode.prototype.getWorldMatrix = function () {
  16280. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16281. this.computeWorldMatrix();
  16282. }
  16283. return this._worldMatrix;
  16284. };
  16285. /**
  16286. * Returns the latest update of the World matrix determinant.
  16287. */
  16288. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16289. return this._worldMatrixDeterminant;
  16290. };
  16291. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16292. /**
  16293. * Returns directly the latest state of the mesh World matrix.
  16294. * A Matrix is returned.
  16295. */
  16296. get: function () {
  16297. return this._worldMatrix;
  16298. },
  16299. enumerable: true,
  16300. configurable: true
  16301. });
  16302. /**
  16303. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16304. * Returns the AbstractMesh.
  16305. */
  16306. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16307. this._poseMatrix.copyFrom(matrix);
  16308. return this;
  16309. };
  16310. /**
  16311. * Returns the mesh Pose matrix.
  16312. * Returned object : Matrix
  16313. */
  16314. TransformNode.prototype.getPoseMatrix = function () {
  16315. return this._poseMatrix;
  16316. };
  16317. TransformNode.prototype._isSynchronized = function () {
  16318. if (this._isDirty) {
  16319. return false;
  16320. }
  16321. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  16322. return false;
  16323. if (this._cache.pivotMatrixUpdated) {
  16324. return false;
  16325. }
  16326. if (this.infiniteDistance) {
  16327. return false;
  16328. }
  16329. if (!this._cache.position.equals(this.position))
  16330. return false;
  16331. if (this.rotationQuaternion) {
  16332. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16333. return false;
  16334. }
  16335. if (!this._cache.rotation.equals(this.rotation))
  16336. return false;
  16337. if (!this._cache.scaling.equals(this.scaling))
  16338. return false;
  16339. return true;
  16340. };
  16341. TransformNode.prototype._initCache = function () {
  16342. _super.prototype._initCache.call(this);
  16343. this._cache.localMatrixUpdated = false;
  16344. this._cache.position = BABYLON.Vector3.Zero();
  16345. this._cache.scaling = BABYLON.Vector3.Zero();
  16346. this._cache.rotation = BABYLON.Vector3.Zero();
  16347. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16348. this._cache.billboardMode = -1;
  16349. };
  16350. TransformNode.prototype.markAsDirty = function (property) {
  16351. if (property === "rotation") {
  16352. this.rotationQuaternion = null;
  16353. }
  16354. this._currentRenderId = Number.MAX_VALUE;
  16355. this._isDirty = true;
  16356. return this;
  16357. };
  16358. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16359. /**
  16360. * Returns the current mesh absolute position.
  16361. * Retuns a Vector3.
  16362. */
  16363. get: function () {
  16364. return this._absolutePosition;
  16365. },
  16366. enumerable: true,
  16367. configurable: true
  16368. });
  16369. /**
  16370. * Sets a new matrix to apply before all other transformation
  16371. * @param matrix defines the transform matrix
  16372. * @returns the current TransformNode
  16373. */
  16374. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16375. return this.setPivotMatrix(matrix, false);
  16376. };
  16377. /**
  16378. * Sets a new pivot matrix to the current node
  16379. * @param matrix defines the new pivot matrix to use
  16380. * @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
  16381. * @returns the current TransformNode
  16382. */
  16383. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16384. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16385. this._pivotMatrix = matrix.clone();
  16386. this._cache.pivotMatrixUpdated = true;
  16387. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16388. if (this._postMultiplyPivotMatrix) {
  16389. if (!this._pivotMatrixInverse) {
  16390. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16391. }
  16392. else {
  16393. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16394. }
  16395. }
  16396. return this;
  16397. };
  16398. /**
  16399. * Returns the mesh pivot matrix.
  16400. * Default : Identity.
  16401. * A Matrix is returned.
  16402. */
  16403. TransformNode.prototype.getPivotMatrix = function () {
  16404. return this._pivotMatrix;
  16405. };
  16406. /**
  16407. * Prevents the World matrix to be computed any longer.
  16408. * Returns the AbstractMesh.
  16409. */
  16410. TransformNode.prototype.freezeWorldMatrix = function () {
  16411. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16412. this.computeWorldMatrix(true);
  16413. this._isWorldMatrixFrozen = true;
  16414. return this;
  16415. };
  16416. /**
  16417. * Allows back the World matrix computation.
  16418. * Returns the AbstractMesh.
  16419. */
  16420. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16421. this._isWorldMatrixFrozen = false;
  16422. this.computeWorldMatrix(true);
  16423. return this;
  16424. };
  16425. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16426. /**
  16427. * True if the World matrix has been frozen.
  16428. * Returns a boolean.
  16429. */
  16430. get: function () {
  16431. return this._isWorldMatrixFrozen;
  16432. },
  16433. enumerable: true,
  16434. configurable: true
  16435. });
  16436. /**
  16437. * Retuns the mesh absolute position in the World.
  16438. * Returns a Vector3.
  16439. */
  16440. TransformNode.prototype.getAbsolutePosition = function () {
  16441. this.computeWorldMatrix();
  16442. return this._absolutePosition;
  16443. };
  16444. /**
  16445. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16446. * Returns the AbstractMesh.
  16447. */
  16448. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16449. if (!absolutePosition) {
  16450. return this;
  16451. }
  16452. var absolutePositionX;
  16453. var absolutePositionY;
  16454. var absolutePositionZ;
  16455. if (absolutePosition.x === undefined) {
  16456. if (arguments.length < 3) {
  16457. return this;
  16458. }
  16459. absolutePositionX = arguments[0];
  16460. absolutePositionY = arguments[1];
  16461. absolutePositionZ = arguments[2];
  16462. }
  16463. else {
  16464. absolutePositionX = absolutePosition.x;
  16465. absolutePositionY = absolutePosition.y;
  16466. absolutePositionZ = absolutePosition.z;
  16467. }
  16468. if (this.parent) {
  16469. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16470. invertParentWorldMatrix.invert();
  16471. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16472. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16473. }
  16474. else {
  16475. this.position.x = absolutePositionX;
  16476. this.position.y = absolutePositionY;
  16477. this.position.z = absolutePositionZ;
  16478. }
  16479. return this;
  16480. };
  16481. /**
  16482. * Sets the mesh position in its local space.
  16483. * Returns the AbstractMesh.
  16484. */
  16485. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16486. this.computeWorldMatrix();
  16487. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16488. return this;
  16489. };
  16490. /**
  16491. * Returns the mesh position in the local space from the current World matrix values.
  16492. * Returns a new Vector3.
  16493. */
  16494. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16495. this.computeWorldMatrix();
  16496. var invLocalWorldMatrix = this._localWorld.clone();
  16497. invLocalWorldMatrix.invert();
  16498. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16499. };
  16500. /**
  16501. * Translates the mesh along the passed Vector3 in its local space.
  16502. * Returns the AbstractMesh.
  16503. */
  16504. TransformNode.prototype.locallyTranslate = function (vector3) {
  16505. this.computeWorldMatrix(true);
  16506. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16507. return this;
  16508. };
  16509. /**
  16510. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16511. * @param targetPoint the position (must be in same space as current mesh) to look at
  16512. * @param yawCor optional yaw (y-axis) correction in radians
  16513. * @param pitchCor optional pitch (x-axis) correction in radians
  16514. * @param rollCor optional roll (z-axis) correction in radians
  16515. * @param space the choosen space of the target
  16516. * @returns the TransformNode.
  16517. */
  16518. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16519. if (yawCor === void 0) { yawCor = 0; }
  16520. if (pitchCor === void 0) { pitchCor = 0; }
  16521. if (rollCor === void 0) { rollCor = 0; }
  16522. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16523. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16524. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16525. targetPoint.subtractToRef(pos, dv);
  16526. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16527. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16528. var pitch = Math.atan2(dv.y, len);
  16529. if (this.rotationQuaternion) {
  16530. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16531. }
  16532. else {
  16533. this.rotation.x = pitch + pitchCor;
  16534. this.rotation.y = yaw + yawCor;
  16535. this.rotation.z = rollCor;
  16536. }
  16537. return this;
  16538. };
  16539. /**
  16540. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16541. * This Vector3 is expressed in the World space.
  16542. */
  16543. TransformNode.prototype.getDirection = function (localAxis) {
  16544. var result = BABYLON.Vector3.Zero();
  16545. this.getDirectionToRef(localAxis, result);
  16546. return result;
  16547. };
  16548. /**
  16549. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16550. * localAxis is expressed in the mesh local space.
  16551. * result is computed in the Wordl space from the mesh World matrix.
  16552. * Returns the AbstractMesh.
  16553. */
  16554. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16555. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16556. return this;
  16557. };
  16558. /**
  16559. * Sets a new pivot point to the current node
  16560. * @param point defines the new pivot point to use
  16561. * @param space defines if the point is in world or local space (local by default)
  16562. * @returns the current TransformNode
  16563. */
  16564. TransformNode.prototype.setPivotPoint = function (point, space) {
  16565. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16566. if (this.getScene().getRenderId() == 0) {
  16567. this.computeWorldMatrix(true);
  16568. }
  16569. var wm = this.getWorldMatrix();
  16570. if (space == BABYLON.Space.WORLD) {
  16571. var tmat = BABYLON.Tmp.Matrix[0];
  16572. wm.invertToRef(tmat);
  16573. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16574. }
  16575. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16576. };
  16577. /**
  16578. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16579. */
  16580. TransformNode.prototype.getPivotPoint = function () {
  16581. var point = BABYLON.Vector3.Zero();
  16582. this.getPivotPointToRef(point);
  16583. return point;
  16584. };
  16585. /**
  16586. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16587. * Returns the AbstractMesh.
  16588. */
  16589. TransformNode.prototype.getPivotPointToRef = function (result) {
  16590. result.x = -this._pivotMatrix.m[12];
  16591. result.y = -this._pivotMatrix.m[13];
  16592. result.z = -this._pivotMatrix.m[14];
  16593. return this;
  16594. };
  16595. /**
  16596. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16597. */
  16598. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16599. var point = BABYLON.Vector3.Zero();
  16600. this.getAbsolutePivotPointToRef(point);
  16601. return point;
  16602. };
  16603. /**
  16604. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16605. * Returns the AbstractMesh.
  16606. */
  16607. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16608. result.x = this._pivotMatrix.m[12];
  16609. result.y = this._pivotMatrix.m[13];
  16610. result.z = this._pivotMatrix.m[14];
  16611. this.getPivotPointToRef(result);
  16612. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16613. return this;
  16614. };
  16615. /**
  16616. * Defines the passed node as the parent of the current node.
  16617. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16618. * Returns the TransformNode.
  16619. */
  16620. TransformNode.prototype.setParent = function (node) {
  16621. if (node === null) {
  16622. var rotation = BABYLON.Tmp.Quaternion[0];
  16623. var position = BABYLON.Tmp.Vector3[0];
  16624. var scale = BABYLON.Tmp.Vector3[1];
  16625. if (this.parent && this.parent.computeWorldMatrix) {
  16626. this.parent.computeWorldMatrix(true);
  16627. }
  16628. this.computeWorldMatrix(true);
  16629. this.getWorldMatrix().decompose(scale, rotation, position);
  16630. if (this.rotationQuaternion) {
  16631. this.rotationQuaternion.copyFrom(rotation);
  16632. }
  16633. else {
  16634. rotation.toEulerAnglesToRef(this.rotation);
  16635. }
  16636. this.scaling.x = scale.x;
  16637. this.scaling.y = scale.y;
  16638. this.scaling.z = scale.z;
  16639. this.position.x = position.x;
  16640. this.position.y = position.y;
  16641. this.position.z = position.z;
  16642. }
  16643. else {
  16644. var rotation = BABYLON.Tmp.Quaternion[0];
  16645. var position = BABYLON.Tmp.Vector3[0];
  16646. var scale = BABYLON.Tmp.Vector3[1];
  16647. var diffMatrix = BABYLON.Tmp.Matrix[0];
  16648. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  16649. this.computeWorldMatrix(true);
  16650. node.computeWorldMatrix(true);
  16651. node.getWorldMatrix().invertToRef(invParentMatrix);
  16652. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  16653. diffMatrix.decompose(scale, rotation, position);
  16654. if (this.rotationQuaternion) {
  16655. this.rotationQuaternion.copyFrom(rotation);
  16656. }
  16657. else {
  16658. rotation.toEulerAnglesToRef(this.rotation);
  16659. }
  16660. this.position.x = position.x;
  16661. this.position.y = position.y;
  16662. this.position.z = position.z;
  16663. this.scaling.x = scale.x;
  16664. this.scaling.y = scale.y;
  16665. this.scaling.z = scale.z;
  16666. }
  16667. this.parent = node;
  16668. return this;
  16669. };
  16670. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  16671. get: function () {
  16672. return this._nonUniformScaling;
  16673. },
  16674. enumerable: true,
  16675. configurable: true
  16676. });
  16677. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  16678. if (this._nonUniformScaling === value) {
  16679. return false;
  16680. }
  16681. this._nonUniformScaling = true;
  16682. return true;
  16683. };
  16684. /**
  16685. * Attach the current TransformNode to another TransformNode associated with a bone
  16686. * @param bone Bone affecting the TransformNode
  16687. * @param affectedTransformNode TransformNode associated with the bone
  16688. */
  16689. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  16690. this._transformToBoneReferal = affectedTransformNode;
  16691. this.parent = bone;
  16692. if (bone.getWorldMatrix().determinant() < 0) {
  16693. this.scalingDeterminant *= -1;
  16694. }
  16695. return this;
  16696. };
  16697. TransformNode.prototype.detachFromBone = function () {
  16698. if (!this.parent) {
  16699. return this;
  16700. }
  16701. if (this.parent.getWorldMatrix().determinant() < 0) {
  16702. this.scalingDeterminant *= -1;
  16703. }
  16704. this._transformToBoneReferal = null;
  16705. this.parent = null;
  16706. return this;
  16707. };
  16708. /**
  16709. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  16710. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16711. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16712. * The passed axis is also normalized.
  16713. * Returns the AbstractMesh.
  16714. */
  16715. TransformNode.prototype.rotate = function (axis, amount, space) {
  16716. axis.normalize();
  16717. if (!this.rotationQuaternion) {
  16718. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16719. this.rotation = BABYLON.Vector3.Zero();
  16720. }
  16721. var rotationQuaternion;
  16722. if (!space || space === BABYLON.Space.LOCAL) {
  16723. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16724. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  16725. }
  16726. else {
  16727. if (this.parent) {
  16728. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16729. invertParentWorldMatrix.invert();
  16730. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  16731. }
  16732. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16733. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16734. }
  16735. return this;
  16736. };
  16737. /**
  16738. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  16739. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16740. * The passed axis is also normalized.
  16741. * Returns the AbstractMesh.
  16742. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  16743. */
  16744. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  16745. axis.normalize();
  16746. if (!this.rotationQuaternion) {
  16747. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16748. this.rotation.copyFromFloats(0, 0, 0);
  16749. }
  16750. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  16751. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  16752. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  16753. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  16754. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  16755. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  16756. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  16757. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  16758. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16759. return this;
  16760. };
  16761. /**
  16762. * Translates the mesh along the axis vector for the passed distance in the given space.
  16763. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16764. * Returns the AbstractMesh.
  16765. */
  16766. TransformNode.prototype.translate = function (axis, distance, space) {
  16767. var displacementVector = axis.scale(distance);
  16768. if (!space || space === BABYLON.Space.LOCAL) {
  16769. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  16770. this.setPositionWithLocalVector(tempV3);
  16771. }
  16772. else {
  16773. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  16774. }
  16775. return this;
  16776. };
  16777. /**
  16778. * Adds a rotation step to the mesh current rotation.
  16779. * x, y, z are Euler angles expressed in radians.
  16780. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  16781. * This means this rotation is made in the mesh local space only.
  16782. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  16783. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  16784. * ```javascript
  16785. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  16786. * ```
  16787. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  16788. * 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.
  16789. * Returns the AbstractMesh.
  16790. */
  16791. TransformNode.prototype.addRotation = function (x, y, z) {
  16792. var rotationQuaternion;
  16793. if (this.rotationQuaternion) {
  16794. rotationQuaternion = this.rotationQuaternion;
  16795. }
  16796. else {
  16797. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  16798. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  16799. }
  16800. var accumulation = BABYLON.Tmp.Quaternion[0];
  16801. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  16802. rotationQuaternion.multiplyInPlace(accumulation);
  16803. if (!this.rotationQuaternion) {
  16804. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  16805. }
  16806. return this;
  16807. };
  16808. /**
  16809. * Computes the mesh World matrix and returns it.
  16810. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  16811. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  16812. * If the parameter `force`is set to `true`, the actual computation is done.
  16813. * Returns the mesh World Matrix.
  16814. */
  16815. TransformNode.prototype.computeWorldMatrix = function (force) {
  16816. if (this._isWorldMatrixFrozen) {
  16817. return this._worldMatrix;
  16818. }
  16819. if (!force && this.isSynchronized(true)) {
  16820. return this._worldMatrix;
  16821. }
  16822. this._cache.position.copyFrom(this.position);
  16823. this._cache.scaling.copyFrom(this.scaling);
  16824. this._cache.pivotMatrixUpdated = false;
  16825. this._cache.billboardMode = this.billboardMode;
  16826. this._currentRenderId = this.getScene().getRenderId();
  16827. this._isDirty = false;
  16828. // Scaling
  16829. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  16830. // Rotation
  16831. //rotate, if quaternion is set and rotation was used
  16832. if (this.rotationQuaternion) {
  16833. var len = this.rotation.length();
  16834. if (len) {
  16835. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  16836. this.rotation.copyFromFloats(0, 0, 0);
  16837. }
  16838. }
  16839. if (this.rotationQuaternion) {
  16840. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  16841. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  16842. }
  16843. else {
  16844. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  16845. this._cache.rotation.copyFrom(this.rotation);
  16846. }
  16847. // Translation
  16848. var camera = this.getScene().activeCamera;
  16849. if (this.infiniteDistance && !this.parent && camera) {
  16850. var cameraWorldMatrix = camera.getWorldMatrix();
  16851. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  16852. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  16853. }
  16854. else {
  16855. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  16856. }
  16857. // Composing transformations
  16858. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  16859. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16860. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  16861. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  16862. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  16863. // Need to decompose each rotation here
  16864. var currentPosition = BABYLON.Tmp.Vector3[3];
  16865. if (this.parent && this.parent.getWorldMatrix) {
  16866. if (this._transformToBoneReferal) {
  16867. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16868. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  16869. }
  16870. else {
  16871. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  16872. }
  16873. }
  16874. else {
  16875. currentPosition.copyFrom(this.position);
  16876. }
  16877. currentPosition.subtractInPlace(camera.globalPosition);
  16878. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  16879. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  16880. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  16881. }
  16882. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  16883. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  16884. }
  16885. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  16886. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  16887. }
  16888. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  16889. }
  16890. else {
  16891. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  16892. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  16893. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  16894. }
  16895. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  16896. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16897. }
  16898. // Local world
  16899. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  16900. // Parent
  16901. if (this.parent && this.parent.getWorldMatrix) {
  16902. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  16903. if (this._transformToBoneReferal) {
  16904. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16905. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  16906. }
  16907. else {
  16908. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  16909. }
  16910. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  16911. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  16912. this._worldMatrix.copyFrom(this._localWorld);
  16913. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  16914. }
  16915. else {
  16916. if (this._transformToBoneReferal) {
  16917. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16918. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  16919. }
  16920. else {
  16921. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  16922. }
  16923. }
  16924. this._markSyncedWithParent();
  16925. }
  16926. else {
  16927. this._worldMatrix.copyFrom(this._localWorld);
  16928. }
  16929. // Post multiply inverse of pivotMatrix
  16930. if (this._postMultiplyPivotMatrix) {
  16931. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  16932. }
  16933. // Normal matrix
  16934. if (this.scaling.isNonUniform) {
  16935. this._updateNonUniformScalingState(true);
  16936. }
  16937. else if (this.parent && this.parent._nonUniformScaling) {
  16938. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  16939. }
  16940. else {
  16941. this._updateNonUniformScalingState(false);
  16942. }
  16943. this._afterComputeWorldMatrix();
  16944. // Absolute position
  16945. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  16946. // Callbacks
  16947. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  16948. if (!this._poseMatrix) {
  16949. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  16950. }
  16951. // Cache the determinant
  16952. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  16953. return this._worldMatrix;
  16954. };
  16955. TransformNode.prototype._afterComputeWorldMatrix = function () {
  16956. };
  16957. /**
  16958. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  16959. * @param func: callback function to add
  16960. *
  16961. * Returns the TransformNode.
  16962. */
  16963. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  16964. this.onAfterWorldMatrixUpdateObservable.add(func);
  16965. return this;
  16966. };
  16967. /**
  16968. * Removes a registered callback function.
  16969. * Returns the TransformNode.
  16970. */
  16971. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  16972. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  16973. return this;
  16974. };
  16975. /**
  16976. * Clone the current transform node
  16977. * Returns the new transform node
  16978. * @param name Name of the new clone
  16979. * @param newParent New parent for the clone
  16980. * @param doNotCloneChildren Do not clone children hierarchy
  16981. */
  16982. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16983. var _this = this;
  16984. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  16985. result.name = name;
  16986. result.id = name;
  16987. if (newParent) {
  16988. result.parent = newParent;
  16989. }
  16990. if (!doNotCloneChildren) {
  16991. // Children
  16992. var directDescendants = this.getDescendants(true);
  16993. for (var index = 0; index < directDescendants.length; index++) {
  16994. var child = directDescendants[index];
  16995. if (child.clone) {
  16996. child.clone(name + "." + child.name, result);
  16997. }
  16998. }
  16999. }
  17000. return result;
  17001. };
  17002. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17003. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17004. serializationObject.type = this.getClassName();
  17005. // Parent
  17006. if (this.parent) {
  17007. serializationObject.parentId = this.parent.id;
  17008. }
  17009. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17010. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17011. }
  17012. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17013. serializationObject.isEnabled = this.isEnabled();
  17014. // Parent
  17015. if (this.parent) {
  17016. serializationObject.parentId = this.parent.id;
  17017. }
  17018. return serializationObject;
  17019. };
  17020. // Statics
  17021. /**
  17022. * Returns a new TransformNode object parsed from the source provided.
  17023. * The parameter `parsedMesh` is the source.
  17024. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17025. */
  17026. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17027. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17028. if (BABYLON.Tags) {
  17029. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17030. }
  17031. if (parsedTransformNode.localMatrix) {
  17032. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17033. }
  17034. else if (parsedTransformNode.pivotMatrix) {
  17035. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17036. }
  17037. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17038. // Parent
  17039. if (parsedTransformNode.parentId) {
  17040. transformNode._waitingParentId = parsedTransformNode.parentId;
  17041. }
  17042. return transformNode;
  17043. };
  17044. /**
  17045. * Disposes the TransformNode.
  17046. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  17047. * Returns nothing.
  17048. */
  17049. TransformNode.prototype.dispose = function (doNotRecurse) {
  17050. // Animations
  17051. this.getScene().stopAnimation(this);
  17052. // Remove from scene
  17053. this.getScene().removeTransformNode(this);
  17054. if (!doNotRecurse) {
  17055. // Children
  17056. var objects = this.getDescendants(true);
  17057. for (var index = 0; index < objects.length; index++) {
  17058. objects[index].dispose();
  17059. }
  17060. }
  17061. else {
  17062. var childMeshes = this.getChildMeshes(true);
  17063. for (index = 0; index < childMeshes.length; index++) {
  17064. var child = childMeshes[index];
  17065. child.parent = null;
  17066. child.computeWorldMatrix(true);
  17067. }
  17068. }
  17069. this.onAfterWorldMatrixUpdateObservable.clear();
  17070. _super.prototype.dispose.call(this);
  17071. };
  17072. // Statics
  17073. TransformNode.BILLBOARDMODE_NONE = 0;
  17074. TransformNode.BILLBOARDMODE_X = 1;
  17075. TransformNode.BILLBOARDMODE_Y = 2;
  17076. TransformNode.BILLBOARDMODE_Z = 4;
  17077. TransformNode.BILLBOARDMODE_ALL = 7;
  17078. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17079. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17080. __decorate([
  17081. BABYLON.serializeAsVector3()
  17082. ], TransformNode.prototype, "_rotation", void 0);
  17083. __decorate([
  17084. BABYLON.serializeAsQuaternion()
  17085. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17086. __decorate([
  17087. BABYLON.serializeAsVector3()
  17088. ], TransformNode.prototype, "_scaling", void 0);
  17089. __decorate([
  17090. BABYLON.serialize()
  17091. ], TransformNode.prototype, "billboardMode", void 0);
  17092. __decorate([
  17093. BABYLON.serialize()
  17094. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17095. __decorate([
  17096. BABYLON.serialize()
  17097. ], TransformNode.prototype, "infiniteDistance", void 0);
  17098. __decorate([
  17099. BABYLON.serializeAsVector3()
  17100. ], TransformNode.prototype, "position", void 0);
  17101. return TransformNode;
  17102. }(BABYLON.Node));
  17103. BABYLON.TransformNode = TransformNode;
  17104. })(BABYLON || (BABYLON = {}));
  17105. //# sourceMappingURL=babylon.transformNode.js.map
  17106. var BABYLON;
  17107. (function (BABYLON) {
  17108. var AbstractMesh = /** @class */ (function (_super) {
  17109. __extends(AbstractMesh, _super);
  17110. // Constructor
  17111. function AbstractMesh(name, scene) {
  17112. if (scene === void 0) { scene = null; }
  17113. var _this = _super.call(this, name, scene, false) || this;
  17114. _this._facetNb = 0; // facet number
  17115. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17116. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17117. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17118. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17119. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17120. _this._subDiv = {
  17121. max: 1,
  17122. X: 1,
  17123. Y: 1,
  17124. Z: 1
  17125. };
  17126. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17127. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17128. // Events
  17129. /**
  17130. * An event triggered when this mesh collides with another one
  17131. * @type {BABYLON.Observable}
  17132. */
  17133. _this.onCollideObservable = new BABYLON.Observable();
  17134. /**
  17135. * An event triggered when the collision's position changes
  17136. * @type {BABYLON.Observable}
  17137. */
  17138. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17139. /**
  17140. * An event triggered when material is changed
  17141. * @type {BABYLON.Observable}
  17142. */
  17143. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17144. // Properties
  17145. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17146. /**
  17147. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17148. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17149. * or
  17150. * 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.
  17151. * for more info check WebGl documentations
  17152. */
  17153. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17154. /**
  17155. * 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:
  17156. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17157. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17158. * 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.
  17159. */
  17160. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17161. /**
  17162. * 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.
  17163. * The default value is -1 which means don't break the query and wait till the result.
  17164. */
  17165. _this.occlusionRetryCount = -1;
  17166. _this._occlusionInternalRetryCounter = 0;
  17167. _this._isOccluded = false;
  17168. _this._isOcclusionQueryInProgress = false;
  17169. _this._visibility = 1.0;
  17170. _this.alphaIndex = Number.MAX_VALUE;
  17171. _this.isVisible = true;
  17172. _this.isPickable = true;
  17173. _this.showBoundingBox = false;
  17174. _this.showSubMeshesBoundingBox = false;
  17175. _this.isBlocker = false;
  17176. _this.enablePointerMoveEvents = false;
  17177. _this.renderingGroupId = 0;
  17178. _this._receiveShadows = false;
  17179. _this.renderOutline = false;
  17180. _this.outlineColor = BABYLON.Color3.Red();
  17181. _this.outlineWidth = 0.02;
  17182. _this.renderOverlay = false;
  17183. _this.overlayColor = BABYLON.Color3.Red();
  17184. _this.overlayAlpha = 0.5;
  17185. _this._hasVertexAlpha = false;
  17186. _this._useVertexColors = true;
  17187. _this._computeBonesUsingShaders = true;
  17188. _this._numBoneInfluencers = 4;
  17189. _this._applyFog = true;
  17190. _this.useOctreeForRenderingSelection = true;
  17191. _this.useOctreeForPicking = true;
  17192. _this.useOctreeForCollisions = true;
  17193. _this._layerMask = 0x0FFFFFFF;
  17194. /**
  17195. * True if the mesh must be rendered in any case.
  17196. */
  17197. _this.alwaysSelectAsActiveMesh = false;
  17198. /**
  17199. * This scene's action manager
  17200. * @type {BABYLON.ActionManager}
  17201. */
  17202. _this.actionManager = null;
  17203. // Physics
  17204. _this.physicsImpostor = null;
  17205. // Collisions
  17206. _this._checkCollisions = false;
  17207. _this._collisionMask = -1;
  17208. _this._collisionGroup = -1;
  17209. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17210. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17211. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17212. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17213. // Edges
  17214. _this.edgesWidth = 1;
  17215. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17216. // Cache
  17217. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17218. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17219. _this._renderId = 0;
  17220. _this._intersectionsInProgress = new Array();
  17221. _this._unIndexed = false;
  17222. _this._lightSources = new Array();
  17223. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17224. if (collidedMesh === void 0) { collidedMesh = null; }
  17225. //TODO move this to the collision coordinator!
  17226. if (_this.getScene().workerCollisions)
  17227. newPosition.multiplyInPlace(_this._collider._radius);
  17228. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17229. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17230. _this.position.addInPlace(_this._diffPositionForCollisions);
  17231. }
  17232. if (collidedMesh) {
  17233. _this.onCollideObservable.notifyObservers(collidedMesh);
  17234. }
  17235. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17236. };
  17237. _this.getScene().addMesh(_this);
  17238. _this._resyncLightSources();
  17239. return _this;
  17240. }
  17241. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17242. get: function () {
  17243. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17244. },
  17245. enumerable: true,
  17246. configurable: true
  17247. });
  17248. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17249. get: function () {
  17250. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17251. },
  17252. enumerable: true,
  17253. configurable: true
  17254. });
  17255. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17256. get: function () {
  17257. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17258. },
  17259. enumerable: true,
  17260. configurable: true
  17261. });
  17262. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17263. get: function () {
  17264. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17265. },
  17266. enumerable: true,
  17267. configurable: true
  17268. });
  17269. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17270. get: function () {
  17271. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17272. },
  17273. enumerable: true,
  17274. configurable: true
  17275. });
  17276. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17277. /**
  17278. * Read-only : the number of facets in the mesh
  17279. */
  17280. get: function () {
  17281. return this._facetNb;
  17282. },
  17283. enumerable: true,
  17284. configurable: true
  17285. });
  17286. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17287. /**
  17288. * The number (integer) of subdivisions per axis in the partioning space
  17289. */
  17290. get: function () {
  17291. return this._partitioningSubdivisions;
  17292. },
  17293. set: function (nb) {
  17294. this._partitioningSubdivisions = nb;
  17295. },
  17296. enumerable: true,
  17297. configurable: true
  17298. });
  17299. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17300. /**
  17301. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17302. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17303. */
  17304. get: function () {
  17305. return this._partitioningBBoxRatio;
  17306. },
  17307. set: function (ratio) {
  17308. this._partitioningBBoxRatio = ratio;
  17309. },
  17310. enumerable: true,
  17311. configurable: true
  17312. });
  17313. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17314. /**
  17315. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17316. * Works only for updatable meshes.
  17317. * Doesn't work with multi-materials.
  17318. */
  17319. get: function () {
  17320. return this._facetDepthSort;
  17321. },
  17322. set: function (sort) {
  17323. this._facetDepthSort = sort;
  17324. },
  17325. enumerable: true,
  17326. configurable: true
  17327. });
  17328. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17329. /**
  17330. * The location (Vector3) where the facet depth sort must be computed from.
  17331. * By default, the active camera position.
  17332. * Used only when facet depth sort is enabled.
  17333. */
  17334. get: function () {
  17335. return this._facetDepthSortFrom;
  17336. },
  17337. set: function (location) {
  17338. this._facetDepthSortFrom = location;
  17339. },
  17340. enumerable: true,
  17341. configurable: true
  17342. });
  17343. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17344. /**
  17345. * Read-only boolean : is the feature facetData enabled ?
  17346. */
  17347. get: function () {
  17348. return this._facetDataEnabled;
  17349. },
  17350. enumerable: true,
  17351. configurable: true
  17352. });
  17353. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17354. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17355. return false;
  17356. }
  17357. this._markSubMeshesAsMiscDirty();
  17358. return true;
  17359. };
  17360. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17361. set: function (callback) {
  17362. if (this._onCollideObserver) {
  17363. this.onCollideObservable.remove(this._onCollideObserver);
  17364. }
  17365. this._onCollideObserver = this.onCollideObservable.add(callback);
  17366. },
  17367. enumerable: true,
  17368. configurable: true
  17369. });
  17370. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17371. set: function (callback) {
  17372. if (this._onCollisionPositionChangeObserver) {
  17373. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17374. }
  17375. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17376. },
  17377. enumerable: true,
  17378. configurable: true
  17379. });
  17380. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17381. /**
  17382. * Property isOccluded : 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.
  17383. */
  17384. get: function () {
  17385. return this._isOccluded;
  17386. },
  17387. set: function (value) {
  17388. this._isOccluded = value;
  17389. },
  17390. enumerable: true,
  17391. configurable: true
  17392. });
  17393. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17394. /**
  17395. * Flag to check the progress status of the query
  17396. */
  17397. get: function () {
  17398. return this._isOcclusionQueryInProgress;
  17399. },
  17400. enumerable: true,
  17401. configurable: true
  17402. });
  17403. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17404. /**
  17405. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17406. */
  17407. get: function () {
  17408. return this._visibility;
  17409. },
  17410. /**
  17411. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17412. */
  17413. set: function (value) {
  17414. if (this._visibility === value) {
  17415. return;
  17416. }
  17417. this._visibility = value;
  17418. this._markSubMeshesAsMiscDirty();
  17419. },
  17420. enumerable: true,
  17421. configurable: true
  17422. });
  17423. Object.defineProperty(AbstractMesh.prototype, "material", {
  17424. get: function () {
  17425. return this._material;
  17426. },
  17427. set: function (value) {
  17428. if (this._material === value) {
  17429. return;
  17430. }
  17431. this._material = value;
  17432. if (this.onMaterialChangedObservable.hasObservers) {
  17433. this.onMaterialChangedObservable.notifyObservers(this);
  17434. }
  17435. if (!this.subMeshes) {
  17436. return;
  17437. }
  17438. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17439. var subMesh = _a[_i];
  17440. subMesh.setEffect(null);
  17441. }
  17442. },
  17443. enumerable: true,
  17444. configurable: true
  17445. });
  17446. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17447. get: function () {
  17448. return this._receiveShadows;
  17449. },
  17450. set: function (value) {
  17451. if (this._receiveShadows === value) {
  17452. return;
  17453. }
  17454. this._receiveShadows = value;
  17455. this._markSubMeshesAsLightDirty();
  17456. },
  17457. enumerable: true,
  17458. configurable: true
  17459. });
  17460. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17461. get: function () {
  17462. return this._hasVertexAlpha;
  17463. },
  17464. set: function (value) {
  17465. if (this._hasVertexAlpha === value) {
  17466. return;
  17467. }
  17468. this._hasVertexAlpha = value;
  17469. this._markSubMeshesAsAttributesDirty();
  17470. this._markSubMeshesAsMiscDirty();
  17471. },
  17472. enumerable: true,
  17473. configurable: true
  17474. });
  17475. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17476. get: function () {
  17477. return this._useVertexColors;
  17478. },
  17479. set: function (value) {
  17480. if (this._useVertexColors === value) {
  17481. return;
  17482. }
  17483. this._useVertexColors = value;
  17484. this._markSubMeshesAsAttributesDirty();
  17485. },
  17486. enumerable: true,
  17487. configurable: true
  17488. });
  17489. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17490. get: function () {
  17491. return this._computeBonesUsingShaders;
  17492. },
  17493. set: function (value) {
  17494. if (this._computeBonesUsingShaders === value) {
  17495. return;
  17496. }
  17497. this._computeBonesUsingShaders = value;
  17498. this._markSubMeshesAsAttributesDirty();
  17499. },
  17500. enumerable: true,
  17501. configurable: true
  17502. });
  17503. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17504. get: function () {
  17505. return this._numBoneInfluencers;
  17506. },
  17507. set: function (value) {
  17508. if (this._numBoneInfluencers === value) {
  17509. return;
  17510. }
  17511. this._numBoneInfluencers = value;
  17512. this._markSubMeshesAsAttributesDirty();
  17513. },
  17514. enumerable: true,
  17515. configurable: true
  17516. });
  17517. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17518. get: function () {
  17519. return this._applyFog;
  17520. },
  17521. set: function (value) {
  17522. if (this._applyFog === value) {
  17523. return;
  17524. }
  17525. this._applyFog = value;
  17526. this._markSubMeshesAsMiscDirty();
  17527. },
  17528. enumerable: true,
  17529. configurable: true
  17530. });
  17531. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17532. get: function () {
  17533. return this._layerMask;
  17534. },
  17535. set: function (value) {
  17536. if (value === this._layerMask) {
  17537. return;
  17538. }
  17539. this._layerMask = value;
  17540. this._resyncLightSources();
  17541. },
  17542. enumerable: true,
  17543. configurable: true
  17544. });
  17545. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17546. get: function () {
  17547. return this._collisionMask;
  17548. },
  17549. set: function (mask) {
  17550. this._collisionMask = !isNaN(mask) ? mask : -1;
  17551. },
  17552. enumerable: true,
  17553. configurable: true
  17554. });
  17555. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17556. get: function () {
  17557. return this._collisionGroup;
  17558. },
  17559. set: function (mask) {
  17560. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17561. },
  17562. enumerable: true,
  17563. configurable: true
  17564. });
  17565. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17566. get: function () {
  17567. return null;
  17568. },
  17569. enumerable: true,
  17570. configurable: true
  17571. });
  17572. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17573. get: function () {
  17574. return this._skeleton;
  17575. },
  17576. set: function (value) {
  17577. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17578. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17579. }
  17580. if (value && value.needInitialSkinMatrix) {
  17581. value._registerMeshWithPoseMatrix(this);
  17582. }
  17583. this._skeleton = value;
  17584. if (!this._skeleton) {
  17585. this._bonesTransformMatrices = null;
  17586. }
  17587. this._markSubMeshesAsAttributesDirty();
  17588. },
  17589. enumerable: true,
  17590. configurable: true
  17591. });
  17592. /**
  17593. * Returns the string "AbstractMesh"
  17594. */
  17595. AbstractMesh.prototype.getClassName = function () {
  17596. return "AbstractMesh";
  17597. };
  17598. /**
  17599. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17600. */
  17601. AbstractMesh.prototype.toString = function (fullDetails) {
  17602. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17603. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17604. if (this._skeleton) {
  17605. ret += ", skeleton: " + this._skeleton.name;
  17606. }
  17607. if (fullDetails) {
  17608. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17609. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17610. }
  17611. return ret;
  17612. };
  17613. AbstractMesh.prototype._rebuild = function () {
  17614. if (this._occlusionQuery) {
  17615. this._occlusionQuery = null;
  17616. }
  17617. if (this._edgesRenderer) {
  17618. this._edgesRenderer._rebuild();
  17619. }
  17620. if (!this.subMeshes) {
  17621. return;
  17622. }
  17623. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17624. var subMesh = _a[_i];
  17625. subMesh._rebuild();
  17626. }
  17627. };
  17628. AbstractMesh.prototype._resyncLightSources = function () {
  17629. this._lightSources.length = 0;
  17630. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17631. var light = _a[_i];
  17632. if (!light.isEnabled()) {
  17633. continue;
  17634. }
  17635. if (light.canAffectMesh(this)) {
  17636. this._lightSources.push(light);
  17637. }
  17638. }
  17639. this._markSubMeshesAsLightDirty();
  17640. };
  17641. AbstractMesh.prototype._resyncLighSource = function (light) {
  17642. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17643. var index = this._lightSources.indexOf(light);
  17644. if (index === -1) {
  17645. if (!isIn) {
  17646. return;
  17647. }
  17648. this._lightSources.push(light);
  17649. }
  17650. else {
  17651. if (isIn) {
  17652. return;
  17653. }
  17654. this._lightSources.splice(index, 1);
  17655. }
  17656. this._markSubMeshesAsLightDirty();
  17657. };
  17658. AbstractMesh.prototype._removeLightSource = function (light) {
  17659. var index = this._lightSources.indexOf(light);
  17660. if (index === -1) {
  17661. return;
  17662. }
  17663. this._lightSources.splice(index, 1);
  17664. this._markSubMeshesAsLightDirty();
  17665. };
  17666. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  17667. if (!this.subMeshes) {
  17668. return;
  17669. }
  17670. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17671. var subMesh = _a[_i];
  17672. if (subMesh._materialDefines) {
  17673. func(subMesh._materialDefines);
  17674. }
  17675. }
  17676. };
  17677. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  17678. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  17679. };
  17680. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  17681. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  17682. };
  17683. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  17684. if (!this.subMeshes) {
  17685. return;
  17686. }
  17687. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17688. var subMesh = _a[_i];
  17689. var material = subMesh.getMaterial();
  17690. if (material) {
  17691. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  17692. }
  17693. }
  17694. };
  17695. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  17696. /**
  17697. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17698. * Default : (1.0, 1.0, 1.0)
  17699. */
  17700. get: function () {
  17701. return this._scaling;
  17702. },
  17703. /**
  17704. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17705. * Default : (1.0, 1.0, 1.0)
  17706. */
  17707. set: function (newScaling) {
  17708. this._scaling = newScaling;
  17709. if (this.physicsImpostor) {
  17710. this.physicsImpostor.forceUpdate();
  17711. }
  17712. },
  17713. enumerable: true,
  17714. configurable: true
  17715. });
  17716. // Methods
  17717. /**
  17718. * Disables the mesh edger rendering mode.
  17719. * Returns the AbstractMesh.
  17720. */
  17721. AbstractMesh.prototype.disableEdgesRendering = function () {
  17722. if (this._edgesRenderer) {
  17723. this._edgesRenderer.dispose();
  17724. this._edgesRenderer = null;
  17725. }
  17726. return this;
  17727. };
  17728. /**
  17729. * Enables the edge rendering mode on the mesh.
  17730. * This mode makes the mesh edges visible.
  17731. * Returns the AbstractMesh.
  17732. */
  17733. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  17734. if (epsilon === void 0) { epsilon = 0.95; }
  17735. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  17736. this.disableEdgesRendering();
  17737. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  17738. return this;
  17739. };
  17740. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  17741. /**
  17742. * Returns true if the mesh is blocked. Used by the class Mesh.
  17743. * Returns the boolean `false` by default.
  17744. */
  17745. get: function () {
  17746. return false;
  17747. },
  17748. enumerable: true,
  17749. configurable: true
  17750. });
  17751. /**
  17752. * Returns the mesh itself by default, used by the class Mesh.
  17753. * Returned type : AbstractMesh
  17754. */
  17755. AbstractMesh.prototype.getLOD = function (camera) {
  17756. return this;
  17757. };
  17758. /**
  17759. * Returns 0 by default, used by the class Mesh.
  17760. * Returns an integer.
  17761. */
  17762. AbstractMesh.prototype.getTotalVertices = function () {
  17763. return 0;
  17764. };
  17765. /**
  17766. * Returns null by default, used by the class Mesh.
  17767. * Returned type : integer array
  17768. */
  17769. AbstractMesh.prototype.getIndices = function () {
  17770. return null;
  17771. };
  17772. /**
  17773. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  17774. * Returned type : float array or Float32Array
  17775. */
  17776. AbstractMesh.prototype.getVerticesData = function (kind) {
  17777. return null;
  17778. };
  17779. /**
  17780. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17781. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  17782. * The `data` are either a numeric array either a Float32Array.
  17783. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  17784. * 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).
  17785. * Note that a new underlying VertexBuffer object is created each call.
  17786. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17787. *
  17788. * Possible `kind` values :
  17789. * - BABYLON.VertexBuffer.PositionKind
  17790. * - BABYLON.VertexBuffer.UVKind
  17791. * - BABYLON.VertexBuffer.UV2Kind
  17792. * - BABYLON.VertexBuffer.UV3Kind
  17793. * - BABYLON.VertexBuffer.UV4Kind
  17794. * - BABYLON.VertexBuffer.UV5Kind
  17795. * - BABYLON.VertexBuffer.UV6Kind
  17796. * - BABYLON.VertexBuffer.ColorKind
  17797. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17798. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17799. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17800. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17801. *
  17802. * Returns the Mesh.
  17803. */
  17804. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17805. return this;
  17806. };
  17807. /**
  17808. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17809. * If the mesh has no geometry, it is simply returned as it is.
  17810. * The `data` are either a numeric array either a Float32Array.
  17811. * No new underlying VertexBuffer object is created.
  17812. * 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.
  17813. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17814. *
  17815. * Possible `kind` values :
  17816. * - BABYLON.VertexBuffer.PositionKind
  17817. * - BABYLON.VertexBuffer.UVKind
  17818. * - BABYLON.VertexBuffer.UV2Kind
  17819. * - BABYLON.VertexBuffer.UV3Kind
  17820. * - BABYLON.VertexBuffer.UV4Kind
  17821. * - BABYLON.VertexBuffer.UV5Kind
  17822. * - BABYLON.VertexBuffer.UV6Kind
  17823. * - BABYLON.VertexBuffer.ColorKind
  17824. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17825. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17826. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17827. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17828. *
  17829. * Returns the Mesh.
  17830. */
  17831. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17832. return this;
  17833. };
  17834. /**
  17835. * Sets the mesh indices.
  17836. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  17837. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  17838. * This method creates a new index buffer each call.
  17839. * Returns the Mesh.
  17840. */
  17841. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  17842. return this;
  17843. };
  17844. /** Returns false by default, used by the class Mesh.
  17845. * Returns a boolean
  17846. */
  17847. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  17848. return false;
  17849. };
  17850. /**
  17851. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  17852. * Returns a BoundingInfo
  17853. */
  17854. AbstractMesh.prototype.getBoundingInfo = function () {
  17855. if (this._masterMesh) {
  17856. return this._masterMesh.getBoundingInfo();
  17857. }
  17858. if (!this._boundingInfo) {
  17859. // this._boundingInfo is being created here
  17860. this._updateBoundingInfo();
  17861. }
  17862. // cannot be null.
  17863. return this._boundingInfo;
  17864. };
  17865. /**
  17866. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  17867. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  17868. */
  17869. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  17870. if (includeDescendants === void 0) { includeDescendants = true; }
  17871. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  17872. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  17873. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  17874. if (maxDimension === 0) {
  17875. return this;
  17876. }
  17877. var scale = 1 / maxDimension;
  17878. this.scaling.scaleInPlace(scale);
  17879. return this;
  17880. };
  17881. /**
  17882. * Sets a mesh new object BoundingInfo.
  17883. * Returns the AbstractMesh.
  17884. */
  17885. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  17886. this._boundingInfo = boundingInfo;
  17887. return this;
  17888. };
  17889. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  17890. get: function () {
  17891. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  17892. },
  17893. enumerable: true,
  17894. configurable: true
  17895. });
  17896. AbstractMesh.prototype._preActivate = function () {
  17897. };
  17898. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  17899. };
  17900. AbstractMesh.prototype._activate = function (renderId) {
  17901. this._renderId = renderId;
  17902. };
  17903. /**
  17904. * Returns the latest update of the World matrix
  17905. * Returns a Matrix.
  17906. */
  17907. AbstractMesh.prototype.getWorldMatrix = function () {
  17908. if (this._masterMesh) {
  17909. return this._masterMesh.getWorldMatrix();
  17910. }
  17911. return _super.prototype.getWorldMatrix.call(this);
  17912. };
  17913. /**
  17914. * Returns the latest update of the World matrix determinant.
  17915. */
  17916. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  17917. if (this._masterMesh) {
  17918. return this._masterMesh._getWorldMatrixDeterminant();
  17919. }
  17920. return _super.prototype._getWorldMatrixDeterminant.call(this);
  17921. };
  17922. // ================================== Point of View Movement =================================
  17923. /**
  17924. * Perform relative position change from the point of view of behind the front of the mesh.
  17925. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17926. * Supports definition of mesh facing forward or backward.
  17927. * @param {number} amountRight
  17928. * @param {number} amountUp
  17929. * @param {number} amountForward
  17930. *
  17931. * Returns the AbstractMesh.
  17932. */
  17933. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  17934. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  17935. return this;
  17936. };
  17937. /**
  17938. * Calculate relative position change from the point of view of behind the front of the mesh.
  17939. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17940. * Supports definition of mesh facing forward or backward.
  17941. * @param {number} amountRight
  17942. * @param {number} amountUp
  17943. * @param {number} amountForward
  17944. *
  17945. * Returns a new Vector3.
  17946. */
  17947. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  17948. var rotMatrix = new BABYLON.Matrix();
  17949. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17950. rotQuaternion.toRotationMatrix(rotMatrix);
  17951. var translationDelta = BABYLON.Vector3.Zero();
  17952. var defForwardMult = this.definedFacingForward ? -1 : 1;
  17953. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  17954. return translationDelta;
  17955. };
  17956. // ================================== Point of View Rotation =================================
  17957. /**
  17958. * Perform relative rotation change from the point of view of behind the front of the mesh.
  17959. * Supports definition of mesh facing forward or backward.
  17960. * @param {number} flipBack
  17961. * @param {number} twirlClockwise
  17962. * @param {number} tiltRight
  17963. *
  17964. * Returns the AbstractMesh.
  17965. */
  17966. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17967. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  17968. return this;
  17969. };
  17970. /**
  17971. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  17972. * Supports definition of mesh facing forward or backward.
  17973. * @param {number} flipBack
  17974. * @param {number} twirlClockwise
  17975. * @param {number} tiltRight
  17976. *
  17977. * Returns a new Vector3.
  17978. */
  17979. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17980. var defForwardMult = this.definedFacingForward ? 1 : -1;
  17981. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  17982. };
  17983. /**
  17984. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  17985. * @param includeDescendants Include bounding info from descendants as well (true by default).
  17986. */
  17987. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  17988. if (includeDescendants === void 0) { includeDescendants = true; }
  17989. this.computeWorldMatrix(true);
  17990. var min;
  17991. var max;
  17992. var boundingInfo = this.getBoundingInfo();
  17993. if (!this.subMeshes) {
  17994. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17995. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  17996. }
  17997. else {
  17998. min = boundingInfo.boundingBox.minimumWorld;
  17999. max = boundingInfo.boundingBox.maximumWorld;
  18000. }
  18001. if (includeDescendants) {
  18002. var descendants = this.getDescendants(false);
  18003. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18004. var descendant = descendants_1[_i];
  18005. var childMesh = descendant;
  18006. childMesh.computeWorldMatrix(true);
  18007. //make sure we have the needed params to get mix and max
  18008. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18009. continue;
  18010. }
  18011. var childBoundingInfo = childMesh.getBoundingInfo();
  18012. var boundingBox = childBoundingInfo.boundingBox;
  18013. var minBox = boundingBox.minimumWorld;
  18014. var maxBox = boundingBox.maximumWorld;
  18015. BABYLON.Tools.CheckExtends(minBox, min, max);
  18016. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18017. }
  18018. }
  18019. return {
  18020. min: min,
  18021. max: max
  18022. };
  18023. };
  18024. /**
  18025. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18026. * Returns the AbstractMesh.
  18027. */
  18028. AbstractMesh.prototype._updateBoundingInfo = function () {
  18029. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18030. this._boundingInfo.update(this.worldMatrixFromCache);
  18031. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18032. return this;
  18033. };
  18034. /**
  18035. * Update a mesh's children BoundingInfo objects only.
  18036. * Returns the AbstractMesh.
  18037. */
  18038. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18039. if (!this.subMeshes) {
  18040. return this;
  18041. }
  18042. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18043. var subMesh = this.subMeshes[subIndex];
  18044. if (!subMesh.IsGlobal) {
  18045. subMesh.updateBoundingInfo(matrix);
  18046. }
  18047. }
  18048. return this;
  18049. };
  18050. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18051. // Bounding info
  18052. this._updateBoundingInfo();
  18053. };
  18054. /**
  18055. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18056. * A mesh is in the frustum if its bounding box intersects the frustum.
  18057. * Boolean returned.
  18058. */
  18059. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18060. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18061. };
  18062. /**
  18063. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18064. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18065. * Boolean returned.
  18066. */
  18067. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18068. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18069. ;
  18070. };
  18071. /**
  18072. * True if the mesh intersects another mesh or a SolidParticle object.
  18073. * 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)
  18074. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18075. * Returns a boolean.
  18076. */
  18077. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18078. if (precise === void 0) { precise = false; }
  18079. if (!this._boundingInfo || !mesh._boundingInfo) {
  18080. return false;
  18081. }
  18082. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18083. return true;
  18084. }
  18085. if (includeDescendants) {
  18086. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18087. var child = _a[_i];
  18088. if (child.intersectsMesh(mesh, precise, true)) {
  18089. return true;
  18090. }
  18091. }
  18092. }
  18093. return false;
  18094. };
  18095. /**
  18096. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18097. * Returns a boolean.
  18098. */
  18099. AbstractMesh.prototype.intersectsPoint = function (point) {
  18100. if (!this._boundingInfo) {
  18101. return false;
  18102. }
  18103. return this._boundingInfo.intersectsPoint(point);
  18104. };
  18105. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18106. return this.physicsImpostor;
  18107. };
  18108. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18109. if (camera === void 0) { camera = null; }
  18110. if (!camera) {
  18111. camera = this.getScene().activeCamera;
  18112. }
  18113. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18114. };
  18115. /**
  18116. * Returns the distance from the mesh to the active camera.
  18117. * Returns a float.
  18118. */
  18119. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18120. if (camera === void 0) { camera = null; }
  18121. if (!camera) {
  18122. camera = this.getScene().activeCamera;
  18123. }
  18124. return this.absolutePosition.subtract(camera.position).length();
  18125. };
  18126. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18127. if (!this.physicsImpostor) {
  18128. return this;
  18129. }
  18130. this.physicsImpostor.applyImpulse(force, contactPoint);
  18131. return this;
  18132. };
  18133. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18134. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18135. return this;
  18136. }
  18137. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18138. mainPivot: pivot1,
  18139. connectedPivot: pivot2,
  18140. nativeParams: options
  18141. });
  18142. return this;
  18143. };
  18144. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18145. // Collisions
  18146. /**
  18147. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18148. * Default `false`.
  18149. */
  18150. get: function () {
  18151. return this._checkCollisions;
  18152. },
  18153. set: function (collisionEnabled) {
  18154. this._checkCollisions = collisionEnabled;
  18155. if (this.getScene().workerCollisions) {
  18156. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18157. }
  18158. },
  18159. enumerable: true,
  18160. configurable: true
  18161. });
  18162. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18163. /**
  18164. * Gets Collider object used to compute collisions (not physics)
  18165. */
  18166. get: function () {
  18167. return this._collider;
  18168. },
  18169. enumerable: true,
  18170. configurable: true
  18171. });
  18172. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18173. var globalPosition = this.getAbsolutePosition();
  18174. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18175. if (!this._collider) {
  18176. this._collider = new BABYLON.Collider();
  18177. }
  18178. this._collider._radius = this.ellipsoid;
  18179. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18180. return this;
  18181. };
  18182. // Submeshes octree
  18183. /**
  18184. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18185. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18186. * Returns an Octree of submeshes.
  18187. */
  18188. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18189. if (maxCapacity === void 0) { maxCapacity = 64; }
  18190. if (maxDepth === void 0) { maxDepth = 2; }
  18191. if (!this._submeshesOctree) {
  18192. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18193. }
  18194. this.computeWorldMatrix(true);
  18195. var boundingInfo = this.getBoundingInfo();
  18196. // Update octree
  18197. var bbox = boundingInfo.boundingBox;
  18198. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18199. return this._submeshesOctree;
  18200. };
  18201. // Collisions
  18202. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18203. this._generatePointsArray();
  18204. if (!this._positions) {
  18205. return this;
  18206. }
  18207. // Transformation
  18208. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18209. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18210. subMesh._lastColliderWorldVertices = [];
  18211. subMesh._trianglePlanes = [];
  18212. var start = subMesh.verticesStart;
  18213. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18214. for (var i = start; i < end; i++) {
  18215. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18216. }
  18217. }
  18218. // Collide
  18219. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18220. if (collider.collisionFound) {
  18221. collider.collidedMesh = this;
  18222. }
  18223. return this;
  18224. };
  18225. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18226. var subMeshes;
  18227. var len;
  18228. // Octrees
  18229. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18230. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18231. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18232. len = intersections.length;
  18233. subMeshes = intersections.data;
  18234. }
  18235. else {
  18236. subMeshes = this.subMeshes;
  18237. len = subMeshes.length;
  18238. }
  18239. for (var index = 0; index < len; index++) {
  18240. var subMesh = subMeshes[index];
  18241. // Bounding test
  18242. if (len > 1 && !subMesh._checkCollision(collider))
  18243. continue;
  18244. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18245. }
  18246. return this;
  18247. };
  18248. AbstractMesh.prototype._checkCollision = function (collider) {
  18249. // Bounding box test
  18250. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18251. return this;
  18252. // Transformation matrix
  18253. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18254. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18255. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18256. return this;
  18257. };
  18258. // Picking
  18259. AbstractMesh.prototype._generatePointsArray = function () {
  18260. return false;
  18261. };
  18262. /**
  18263. * Checks if the passed Ray intersects with the mesh.
  18264. * Returns an object PickingInfo.
  18265. */
  18266. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18267. var pickingInfo = new BABYLON.PickingInfo();
  18268. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18269. return pickingInfo;
  18270. }
  18271. if (!this._generatePointsArray()) {
  18272. return pickingInfo;
  18273. }
  18274. var intersectInfo = null;
  18275. // Octrees
  18276. var subMeshes;
  18277. var len;
  18278. if (this._submeshesOctree && this.useOctreeForPicking) {
  18279. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18280. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18281. len = intersections.length;
  18282. subMeshes = intersections.data;
  18283. }
  18284. else {
  18285. subMeshes = this.subMeshes;
  18286. len = subMeshes.length;
  18287. }
  18288. for (var index = 0; index < len; index++) {
  18289. var subMesh = subMeshes[index];
  18290. // Bounding test
  18291. if (len > 1 && !subMesh.canIntersects(ray))
  18292. continue;
  18293. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18294. if (currentIntersectInfo) {
  18295. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18296. intersectInfo = currentIntersectInfo;
  18297. intersectInfo.subMeshId = index;
  18298. if (fastCheck) {
  18299. break;
  18300. }
  18301. }
  18302. }
  18303. }
  18304. if (intersectInfo) {
  18305. // Get picked point
  18306. var world = this.getWorldMatrix();
  18307. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18308. var direction = ray.direction.clone();
  18309. direction = direction.scale(intersectInfo.distance);
  18310. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18311. var pickedPoint = worldOrigin.add(worldDirection);
  18312. // Return result
  18313. pickingInfo.hit = true;
  18314. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18315. pickingInfo.pickedPoint = pickedPoint;
  18316. pickingInfo.pickedMesh = this;
  18317. pickingInfo.bu = intersectInfo.bu || 0;
  18318. pickingInfo.bv = intersectInfo.bv || 0;
  18319. pickingInfo.faceId = intersectInfo.faceId;
  18320. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18321. return pickingInfo;
  18322. }
  18323. return pickingInfo;
  18324. };
  18325. /**
  18326. * Clones the mesh, used by the class Mesh.
  18327. * Just returns `null` for an AbstractMesh.
  18328. */
  18329. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18330. return null;
  18331. };
  18332. /**
  18333. * Disposes all the mesh submeshes.
  18334. * Returns the AbstractMesh.
  18335. */
  18336. AbstractMesh.prototype.releaseSubMeshes = function () {
  18337. if (this.subMeshes) {
  18338. while (this.subMeshes.length) {
  18339. this.subMeshes[0].dispose();
  18340. }
  18341. }
  18342. else {
  18343. this.subMeshes = new Array();
  18344. }
  18345. return this;
  18346. };
  18347. /**
  18348. * Disposes the AbstractMesh.
  18349. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  18350. * Returns nothing.
  18351. */
  18352. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18353. var _this = this;
  18354. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18355. var index;
  18356. // Action manager
  18357. if (this.actionManager !== undefined && this.actionManager !== null) {
  18358. this.actionManager.dispose();
  18359. this.actionManager = null;
  18360. }
  18361. // Skeleton
  18362. this.skeleton = null;
  18363. // Physics
  18364. if (this.physicsImpostor) {
  18365. this.physicsImpostor.dispose();
  18366. }
  18367. // Intersections in progress
  18368. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18369. var other = this._intersectionsInProgress[index];
  18370. var pos = other._intersectionsInProgress.indexOf(this);
  18371. other._intersectionsInProgress.splice(pos, 1);
  18372. }
  18373. this._intersectionsInProgress = [];
  18374. // Lights
  18375. var lights = this.getScene().lights;
  18376. lights.forEach(function (light) {
  18377. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18378. if (meshIndex !== -1) {
  18379. light.includedOnlyMeshes.splice(meshIndex, 1);
  18380. }
  18381. meshIndex = light.excludedMeshes.indexOf(_this);
  18382. if (meshIndex !== -1) {
  18383. light.excludedMeshes.splice(meshIndex, 1);
  18384. }
  18385. // Shadow generators
  18386. var generator = light.getShadowGenerator();
  18387. if (generator) {
  18388. var shadowMap = generator.getShadowMap();
  18389. if (shadowMap && shadowMap.renderList) {
  18390. meshIndex = shadowMap.renderList.indexOf(_this);
  18391. if (meshIndex !== -1) {
  18392. shadowMap.renderList.splice(meshIndex, 1);
  18393. }
  18394. }
  18395. }
  18396. });
  18397. // Edges
  18398. if (this._edgesRenderer) {
  18399. this._edgesRenderer.dispose();
  18400. this._edgesRenderer = null;
  18401. }
  18402. // SubMeshes
  18403. if (this.getClassName() !== "InstancedMesh") {
  18404. this.releaseSubMeshes();
  18405. }
  18406. // Octree
  18407. var sceneOctree = this.getScene().selectionOctree;
  18408. if (sceneOctree !== undefined && sceneOctree !== null) {
  18409. var index = sceneOctree.dynamicContent.indexOf(this);
  18410. if (index !== -1) {
  18411. sceneOctree.dynamicContent.splice(index, 1);
  18412. }
  18413. }
  18414. // Query
  18415. var engine = this.getScene().getEngine();
  18416. if (this._occlusionQuery) {
  18417. this._isOcclusionQueryInProgress = false;
  18418. engine.deleteQuery(this._occlusionQuery);
  18419. this._occlusionQuery = null;
  18420. }
  18421. // Engine
  18422. engine.wipeCaches();
  18423. // Remove from scene
  18424. this.getScene().removeMesh(this);
  18425. if (disposeMaterialAndTextures) {
  18426. if (this.material) {
  18427. this.material.dispose(false, true);
  18428. }
  18429. }
  18430. if (!doNotRecurse) {
  18431. // Particles
  18432. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18433. if (this.getScene().particleSystems[index].emitter === this) {
  18434. this.getScene().particleSystems[index].dispose();
  18435. index--;
  18436. }
  18437. }
  18438. }
  18439. // facet data
  18440. if (this._facetDataEnabled) {
  18441. this.disableFacetData();
  18442. }
  18443. this.onAfterWorldMatrixUpdateObservable.clear();
  18444. this.onCollideObservable.clear();
  18445. this.onCollisionPositionChangeObservable.clear();
  18446. _super.prototype.dispose.call(this, doNotRecurse);
  18447. };
  18448. /**
  18449. * Adds the passed mesh as a child to the current mesh.
  18450. * Returns the AbstractMesh.
  18451. */
  18452. AbstractMesh.prototype.addChild = function (mesh) {
  18453. mesh.setParent(this);
  18454. return this;
  18455. };
  18456. /**
  18457. * Removes the passed mesh from the current mesh children list.
  18458. * Returns the AbstractMesh.
  18459. */
  18460. AbstractMesh.prototype.removeChild = function (mesh) {
  18461. mesh.setParent(null);
  18462. return this;
  18463. };
  18464. // Facet data
  18465. /**
  18466. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18467. * Returns the AbstractMesh.
  18468. */
  18469. AbstractMesh.prototype._initFacetData = function () {
  18470. if (!this._facetNormals) {
  18471. this._facetNormals = new Array();
  18472. }
  18473. if (!this._facetPositions) {
  18474. this._facetPositions = new Array();
  18475. }
  18476. if (!this._facetPartitioning) {
  18477. this._facetPartitioning = new Array();
  18478. }
  18479. this._facetNb = (this.getIndices().length / 3) | 0;
  18480. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18481. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18482. for (var f = 0; f < this._facetNb; f++) {
  18483. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18484. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18485. }
  18486. this._facetDataEnabled = true;
  18487. return this;
  18488. };
  18489. /**
  18490. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18491. * This method can be called within the render loop.
  18492. * 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.
  18493. * Returns the AbstractMesh.
  18494. */
  18495. AbstractMesh.prototype.updateFacetData = function () {
  18496. if (!this._facetDataEnabled) {
  18497. this._initFacetData();
  18498. }
  18499. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18500. var indices = this.getIndices();
  18501. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18502. var bInfo = this.getBoundingInfo();
  18503. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18504. // init arrays, matrix and sort function on first call
  18505. this._facetDepthSortEnabled = true;
  18506. if (indices instanceof Uint16Array) {
  18507. this._depthSortedIndices = new Uint16Array(indices);
  18508. }
  18509. else if (indices instanceof Uint32Array) {
  18510. this._depthSortedIndices = new Uint32Array(indices);
  18511. }
  18512. else {
  18513. var needs32bits = false;
  18514. for (var i = 0; i < indices.length; i++) {
  18515. if (indices[i] > 65535) {
  18516. needs32bits = true;
  18517. break;
  18518. }
  18519. }
  18520. if (needs32bits) {
  18521. this._depthSortedIndices = new Uint32Array(indices);
  18522. }
  18523. else {
  18524. this._depthSortedIndices = new Uint16Array(indices);
  18525. }
  18526. }
  18527. this._facetDepthSortFunction = function (f1, f2) {
  18528. return (f2.sqDistance - f1.sqDistance);
  18529. };
  18530. if (!this._facetDepthSortFrom) {
  18531. var camera = this.getScene().activeCamera;
  18532. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18533. }
  18534. this._depthSortedFacets = [];
  18535. for (var f = 0; f < this._facetNb; f++) {
  18536. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18537. this._depthSortedFacets.push(depthSortedFacet);
  18538. }
  18539. this._invertedMatrix = BABYLON.Matrix.Identity();
  18540. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18541. }
  18542. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18543. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18544. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18545. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18546. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18547. this._subDiv.max = this._partitioningSubdivisions;
  18548. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18549. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18550. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18551. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18552. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18553. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18554. // set the parameters for ComputeNormals()
  18555. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18556. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18557. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18558. this._facetParameters.bInfo = bInfo;
  18559. this._facetParameters.bbSize = this._bbSize;
  18560. this._facetParameters.subDiv = this._subDiv;
  18561. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18562. this._facetParameters.depthSort = this._facetDepthSort;
  18563. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18564. this.computeWorldMatrix(true);
  18565. this._worldMatrix.invertToRef(this._invertedMatrix);
  18566. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18567. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18568. }
  18569. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18570. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18571. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18572. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18573. var l = (this._depthSortedIndices.length / 3) | 0;
  18574. for (var f = 0; f < l; f++) {
  18575. var sind = this._depthSortedFacets[f].ind;
  18576. this._depthSortedIndices[f * 3] = indices[sind];
  18577. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18578. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18579. }
  18580. this.updateIndices(this._depthSortedIndices);
  18581. }
  18582. return this;
  18583. };
  18584. /**
  18585. * Returns the facetLocalNormals array.
  18586. * The normals are expressed in the mesh local space.
  18587. */
  18588. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18589. if (!this._facetNormals) {
  18590. this.updateFacetData();
  18591. }
  18592. return this._facetNormals;
  18593. };
  18594. /**
  18595. * Returns the facetLocalPositions array.
  18596. * The facet positions are expressed in the mesh local space.
  18597. */
  18598. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18599. if (!this._facetPositions) {
  18600. this.updateFacetData();
  18601. }
  18602. return this._facetPositions;
  18603. };
  18604. /**
  18605. * Returns the facetLocalPartioning array.
  18606. */
  18607. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18608. if (!this._facetPartitioning) {
  18609. this.updateFacetData();
  18610. }
  18611. return this._facetPartitioning;
  18612. };
  18613. /**
  18614. * Returns the i-th facet position in the world system.
  18615. * This method allocates a new Vector3 per call.
  18616. */
  18617. AbstractMesh.prototype.getFacetPosition = function (i) {
  18618. var pos = BABYLON.Vector3.Zero();
  18619. this.getFacetPositionToRef(i, pos);
  18620. return pos;
  18621. };
  18622. /**
  18623. * Sets the reference Vector3 with the i-th facet position in the world system.
  18624. * Returns the AbstractMesh.
  18625. */
  18626. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18627. var localPos = (this.getFacetLocalPositions())[i];
  18628. var world = this.getWorldMatrix();
  18629. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18630. return this;
  18631. };
  18632. /**
  18633. * Returns the i-th facet normal in the world system.
  18634. * This method allocates a new Vector3 per call.
  18635. */
  18636. AbstractMesh.prototype.getFacetNormal = function (i) {
  18637. var norm = BABYLON.Vector3.Zero();
  18638. this.getFacetNormalToRef(i, norm);
  18639. return norm;
  18640. };
  18641. /**
  18642. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18643. * Returns the AbstractMesh.
  18644. */
  18645. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18646. var localNorm = (this.getFacetLocalNormals())[i];
  18647. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18648. return this;
  18649. };
  18650. /**
  18651. * 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).
  18652. */
  18653. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18654. var bInfo = this.getBoundingInfo();
  18655. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18656. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18657. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  18658. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  18659. return null;
  18660. }
  18661. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  18662. };
  18663. /**
  18664. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  18665. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  18666. * If checkFace is 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.
  18667. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18668. * 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.
  18669. */
  18670. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  18671. if (checkFace === void 0) { checkFace = false; }
  18672. if (facing === void 0) { facing = true; }
  18673. var world = this.getWorldMatrix();
  18674. var invMat = BABYLON.Tmp.Matrix[5];
  18675. world.invertToRef(invMat);
  18676. var invVect = BABYLON.Tmp.Vector3[8];
  18677. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  18678. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  18679. if (projected) {
  18680. // tranform the local computed projected vector to world coordinates
  18681. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  18682. }
  18683. return closest;
  18684. };
  18685. /**
  18686. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  18687. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  18688. * If checkFace is 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.
  18689. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18690. * 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.
  18691. */
  18692. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  18693. if (checkFace === void 0) { checkFace = false; }
  18694. if (facing === void 0) { facing = true; }
  18695. var closest = null;
  18696. var tmpx = 0.0;
  18697. var tmpy = 0.0;
  18698. var tmpz = 0.0;
  18699. var d = 0.0; // tmp dot facet normal * facet position
  18700. var t0 = 0.0;
  18701. var projx = 0.0;
  18702. var projy = 0.0;
  18703. var projz = 0.0;
  18704. // Get all the facets in the same partitioning block than (x, y, z)
  18705. var facetPositions = this.getFacetLocalPositions();
  18706. var facetNormals = this.getFacetLocalNormals();
  18707. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  18708. if (!facetsInBlock) {
  18709. return null;
  18710. }
  18711. // Get the closest facet to (x, y, z)
  18712. var shortest = Number.MAX_VALUE; // init distance vars
  18713. var tmpDistance = shortest;
  18714. var fib; // current facet in the block
  18715. var norm; // current facet normal
  18716. var p0; // current facet barycenter position
  18717. // loop on all the facets in the current partitioning block
  18718. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  18719. fib = facetsInBlock[idx];
  18720. norm = facetNormals[fib];
  18721. p0 = facetPositions[fib];
  18722. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  18723. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  18724. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  18725. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  18726. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  18727. projx = x + norm.x * t0;
  18728. projy = y + norm.y * t0;
  18729. projz = z + norm.z * t0;
  18730. tmpx = projx - x;
  18731. tmpy = projy - y;
  18732. tmpz = projz - z;
  18733. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  18734. if (tmpDistance < shortest) {
  18735. shortest = tmpDistance;
  18736. closest = fib;
  18737. if (projected) {
  18738. projected.x = projx;
  18739. projected.y = projy;
  18740. projected.z = projz;
  18741. }
  18742. }
  18743. }
  18744. }
  18745. return closest;
  18746. };
  18747. /**
  18748. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  18749. */
  18750. AbstractMesh.prototype.getFacetDataParameters = function () {
  18751. return this._facetParameters;
  18752. };
  18753. /**
  18754. * Disables the feature FacetData and frees the related memory.
  18755. * Returns the AbstractMesh.
  18756. */
  18757. AbstractMesh.prototype.disableFacetData = function () {
  18758. if (this._facetDataEnabled) {
  18759. this._facetDataEnabled = false;
  18760. this._facetPositions = new Array();
  18761. this._facetNormals = new Array();
  18762. this._facetPartitioning = new Array();
  18763. this._facetParameters = null;
  18764. this._depthSortedIndices = new Uint32Array(0);
  18765. }
  18766. return this;
  18767. };
  18768. /**
  18769. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  18770. * Returns the mesh.
  18771. */
  18772. AbstractMesh.prototype.updateIndices = function (indices) {
  18773. return this;
  18774. };
  18775. /**
  18776. * The mesh Geometry. Actually used by the Mesh object.
  18777. * Returns a blank geometry object.
  18778. */
  18779. /**
  18780. * Creates new normals data for the mesh.
  18781. * @param updatable.
  18782. */
  18783. AbstractMesh.prototype.createNormals = function (updatable) {
  18784. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18785. var indices = this.getIndices();
  18786. var normals;
  18787. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18788. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18789. }
  18790. else {
  18791. normals = [];
  18792. }
  18793. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  18794. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  18795. };
  18796. /**
  18797. * Align the mesh with a normal.
  18798. * Returns the mesh.
  18799. */
  18800. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  18801. if (!upDirection) {
  18802. upDirection = BABYLON.Axis.Y;
  18803. }
  18804. var axisX = BABYLON.Tmp.Vector3[0];
  18805. var axisZ = BABYLON.Tmp.Vector3[1];
  18806. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  18807. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  18808. if (this.rotationQuaternion) {
  18809. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  18810. }
  18811. else {
  18812. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  18813. }
  18814. return this;
  18815. };
  18816. AbstractMesh.prototype.checkOcclusionQuery = function () {
  18817. var engine = this.getEngine();
  18818. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  18819. this._isOccluded = false;
  18820. return;
  18821. }
  18822. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  18823. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  18824. if (isOcclusionQueryAvailable) {
  18825. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  18826. this._isOcclusionQueryInProgress = false;
  18827. this._occlusionInternalRetryCounter = 0;
  18828. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  18829. }
  18830. else {
  18831. this._occlusionInternalRetryCounter++;
  18832. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  18833. this._isOcclusionQueryInProgress = false;
  18834. this._occlusionInternalRetryCounter = 0;
  18835. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  18836. // if strict continue the last state of the object.
  18837. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  18838. }
  18839. else {
  18840. return;
  18841. }
  18842. }
  18843. }
  18844. var scene = this.getScene();
  18845. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  18846. if (!this._occlusionQuery) {
  18847. this._occlusionQuery = engine.createQuery();
  18848. }
  18849. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  18850. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  18851. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  18852. this._isOcclusionQueryInProgress = true;
  18853. };
  18854. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  18855. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  18856. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  18857. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  18858. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  18859. return AbstractMesh;
  18860. }(BABYLON.TransformNode));
  18861. BABYLON.AbstractMesh = AbstractMesh;
  18862. })(BABYLON || (BABYLON = {}));
  18863. //# sourceMappingURL=babylon.abstractMesh.js.map
  18864. var BABYLON;
  18865. (function (BABYLON) {
  18866. /**
  18867. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  18868. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  18869. * 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.
  18870. */
  18871. var Light = /** @class */ (function (_super) {
  18872. __extends(Light, _super);
  18873. /**
  18874. * Creates a Light object in the scene.
  18875. * Documentation : http://doc.babylonjs.com/tutorials/lights
  18876. * @param name The firendly name of the light
  18877. * @param scene The scene the light belongs too
  18878. */
  18879. function Light(name, scene) {
  18880. var _this = _super.call(this, name, scene) || this;
  18881. /**
  18882. * Diffuse gives the basic color to an object.
  18883. */
  18884. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  18885. /**
  18886. * Specular produces a highlight color on an object.
  18887. * Note: This is note affecting PBR materials.
  18888. */
  18889. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  18890. /**
  18891. * Strength of the light.
  18892. * Note: By default it is define in the framework own unit.
  18893. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  18894. */
  18895. _this.intensity = 1.0;
  18896. /**
  18897. * Defines how far from the source the light is impacting in scene units.
  18898. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  18899. */
  18900. _this.range = Number.MAX_VALUE;
  18901. /**
  18902. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  18903. * of light.
  18904. */
  18905. _this._photometricScale = 1.0;
  18906. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  18907. _this._radius = 0.00001;
  18908. /**
  18909. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  18910. * exceeding the number allowed of the materials.
  18911. */
  18912. _this.renderPriority = 0;
  18913. /**
  18914. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  18915. * the current shadow generator.
  18916. */
  18917. _this.shadowEnabled = true;
  18918. _this._excludeWithLayerMask = 0;
  18919. _this._includeOnlyWithLayerMask = 0;
  18920. _this._lightmapMode = 0;
  18921. /**
  18922. * @ignore Internal use only.
  18923. */
  18924. _this._excludedMeshesIds = new Array();
  18925. /**
  18926. * @ignore Internal use only.
  18927. */
  18928. _this._includedOnlyMeshesIds = new Array();
  18929. _this.getScene().addLight(_this);
  18930. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  18931. _this._buildUniformLayout();
  18932. _this.includedOnlyMeshes = new Array();
  18933. _this.excludedMeshes = new Array();
  18934. _this._resyncMeshes();
  18935. return _this;
  18936. }
  18937. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  18938. /**
  18939. * If every light affecting the material is in this lightmapMode,
  18940. * material.lightmapTexture adds or multiplies
  18941. * (depends on material.useLightmapAsShadowmap)
  18942. * after every other light calculations.
  18943. */
  18944. get: function () {
  18945. return Light._LIGHTMAP_DEFAULT;
  18946. },
  18947. enumerable: true,
  18948. configurable: true
  18949. });
  18950. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  18951. /**
  18952. * material.lightmapTexture as only diffuse lighting from this light
  18953. * adds only specular lighting from this light
  18954. * adds dynamic shadows
  18955. */
  18956. get: function () {
  18957. return Light._LIGHTMAP_SPECULAR;
  18958. },
  18959. enumerable: true,
  18960. configurable: true
  18961. });
  18962. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  18963. /**
  18964. * material.lightmapTexture as only lighting
  18965. * no light calculation from this light
  18966. * only adds dynamic shadows from this light
  18967. */
  18968. get: function () {
  18969. return Light._LIGHTMAP_SHADOWSONLY;
  18970. },
  18971. enumerable: true,
  18972. configurable: true
  18973. });
  18974. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  18975. /**
  18976. * Each light type uses the default quantity according to its type:
  18977. * point/spot lights use luminous intensity
  18978. * directional lights use illuminance
  18979. */
  18980. get: function () {
  18981. return Light._INTENSITYMODE_AUTOMATIC;
  18982. },
  18983. enumerable: true,
  18984. configurable: true
  18985. });
  18986. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  18987. /**
  18988. * lumen (lm)
  18989. */
  18990. get: function () {
  18991. return Light._INTENSITYMODE_LUMINOUSPOWER;
  18992. },
  18993. enumerable: true,
  18994. configurable: true
  18995. });
  18996. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  18997. /**
  18998. * candela (lm/sr)
  18999. */
  19000. get: function () {
  19001. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19002. },
  19003. enumerable: true,
  19004. configurable: true
  19005. });
  19006. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19007. /**
  19008. * lux (lm/m^2)
  19009. */
  19010. get: function () {
  19011. return Light._INTENSITYMODE_ILLUMINANCE;
  19012. },
  19013. enumerable: true,
  19014. configurable: true
  19015. });
  19016. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19017. /**
  19018. * nit (cd/m^2)
  19019. */
  19020. get: function () {
  19021. return Light._INTENSITYMODE_LUMINANCE;
  19022. },
  19023. enumerable: true,
  19024. configurable: true
  19025. });
  19026. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19027. /**
  19028. * Light type const id of the point light.
  19029. */
  19030. get: function () {
  19031. return Light._LIGHTTYPEID_POINTLIGHT;
  19032. },
  19033. enumerable: true,
  19034. configurable: true
  19035. });
  19036. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19037. /**
  19038. * Light type const id of the directional light.
  19039. */
  19040. get: function () {
  19041. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19042. },
  19043. enumerable: true,
  19044. configurable: true
  19045. });
  19046. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19047. /**
  19048. * Light type const id of the spot light.
  19049. */
  19050. get: function () {
  19051. return Light._LIGHTTYPEID_SPOTLIGHT;
  19052. },
  19053. enumerable: true,
  19054. configurable: true
  19055. });
  19056. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19057. /**
  19058. * Light type const id of the hemispheric light.
  19059. */
  19060. get: function () {
  19061. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19062. },
  19063. enumerable: true,
  19064. configurable: true
  19065. });
  19066. Object.defineProperty(Light.prototype, "intensityMode", {
  19067. /**
  19068. * Gets the photometric scale used to interpret the intensity.
  19069. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19070. */
  19071. get: function () {
  19072. return this._intensityMode;
  19073. },
  19074. /**
  19075. * Sets the photometric scale used to interpret the intensity.
  19076. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19077. */
  19078. set: function (value) {
  19079. this._intensityMode = value;
  19080. this._computePhotometricScale();
  19081. },
  19082. enumerable: true,
  19083. configurable: true
  19084. });
  19085. ;
  19086. ;
  19087. Object.defineProperty(Light.prototype, "radius", {
  19088. /**
  19089. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19090. */
  19091. get: function () {
  19092. return this._radius;
  19093. },
  19094. /**
  19095. * sets the light radius used by PBR Materials to simulate soft area lights.
  19096. */
  19097. set: function (value) {
  19098. this._radius = value;
  19099. this._computePhotometricScale();
  19100. },
  19101. enumerable: true,
  19102. configurable: true
  19103. });
  19104. ;
  19105. ;
  19106. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19107. /**
  19108. * Gets the only meshes impacted by this light.
  19109. */
  19110. get: function () {
  19111. return this._includedOnlyMeshes;
  19112. },
  19113. /**
  19114. * Sets the only meshes impacted by this light.
  19115. */
  19116. set: function (value) {
  19117. this._includedOnlyMeshes = value;
  19118. this._hookArrayForIncludedOnly(value);
  19119. },
  19120. enumerable: true,
  19121. configurable: true
  19122. });
  19123. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19124. /**
  19125. * Gets the meshes not impacted by this light.
  19126. */
  19127. get: function () {
  19128. return this._excludedMeshes;
  19129. },
  19130. /**
  19131. * Sets the meshes not impacted by this light.
  19132. */
  19133. set: function (value) {
  19134. this._excludedMeshes = value;
  19135. this._hookArrayForExcluded(value);
  19136. },
  19137. enumerable: true,
  19138. configurable: true
  19139. });
  19140. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19141. /**
  19142. * Gets the layer id use to find what meshes are not impacted by the light.
  19143. * Inactive if 0
  19144. */
  19145. get: function () {
  19146. return this._excludeWithLayerMask;
  19147. },
  19148. /**
  19149. * Sets the layer id use to find what meshes are not impacted by the light.
  19150. * Inactive if 0
  19151. */
  19152. set: function (value) {
  19153. this._excludeWithLayerMask = value;
  19154. this._resyncMeshes();
  19155. },
  19156. enumerable: true,
  19157. configurable: true
  19158. });
  19159. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19160. /**
  19161. * Gets the layer id use to find what meshes are impacted by the light.
  19162. * Inactive if 0
  19163. */
  19164. get: function () {
  19165. return this._includeOnlyWithLayerMask;
  19166. },
  19167. /**
  19168. * Sets the layer id use to find what meshes are impacted by the light.
  19169. * Inactive if 0
  19170. */
  19171. set: function (value) {
  19172. this._includeOnlyWithLayerMask = value;
  19173. this._resyncMeshes();
  19174. },
  19175. enumerable: true,
  19176. configurable: true
  19177. });
  19178. Object.defineProperty(Light.prototype, "lightmapMode", {
  19179. /**
  19180. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19181. */
  19182. get: function () {
  19183. return this._lightmapMode;
  19184. },
  19185. /**
  19186. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19187. */
  19188. set: function (value) {
  19189. if (this._lightmapMode === value) {
  19190. return;
  19191. }
  19192. this._lightmapMode = value;
  19193. this._markMeshesAsLightDirty();
  19194. },
  19195. enumerable: true,
  19196. configurable: true
  19197. });
  19198. /**
  19199. * Returns the string "Light".
  19200. * @returns the class name
  19201. */
  19202. Light.prototype.getClassName = function () {
  19203. return "Light";
  19204. };
  19205. /**
  19206. * Converts the light information to a readable string for debug purpose.
  19207. * @param fullDetails Supports for multiple levels of logging within scene loading
  19208. * @returns the human readable light info
  19209. */
  19210. Light.prototype.toString = function (fullDetails) {
  19211. var ret = "Name: " + this.name;
  19212. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19213. if (this.animations) {
  19214. for (var i = 0; i < this.animations.length; i++) {
  19215. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19216. }
  19217. }
  19218. if (fullDetails) {
  19219. }
  19220. return ret;
  19221. };
  19222. /**
  19223. * Set the enabled state of this node.
  19224. * @param value - the new enabled state
  19225. * @see isEnabled
  19226. */
  19227. Light.prototype.setEnabled = function (value) {
  19228. _super.prototype.setEnabled.call(this, value);
  19229. this._resyncMeshes();
  19230. };
  19231. /**
  19232. * Returns the Light associated shadow generator if any.
  19233. * @return the associated shadow generator.
  19234. */
  19235. Light.prototype.getShadowGenerator = function () {
  19236. return this._shadowGenerator;
  19237. };
  19238. /**
  19239. * Returns a Vector3, the absolute light position in the World.
  19240. * @returns the world space position of the light
  19241. */
  19242. Light.prototype.getAbsolutePosition = function () {
  19243. return BABYLON.Vector3.Zero();
  19244. };
  19245. /**
  19246. * Specifies if the light will affect the passed mesh.
  19247. * @param mesh The mesh to test against the light
  19248. * @return true the mesh is affected otherwise, false.
  19249. */
  19250. Light.prototype.canAffectMesh = function (mesh) {
  19251. if (!mesh) {
  19252. return true;
  19253. }
  19254. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19255. return false;
  19256. }
  19257. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19258. return false;
  19259. }
  19260. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19261. return false;
  19262. }
  19263. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19264. return false;
  19265. }
  19266. return true;
  19267. };
  19268. /**
  19269. * Computes and Returns the light World matrix.
  19270. * @returns the world matrix
  19271. */
  19272. Light.prototype.getWorldMatrix = function () {
  19273. this._currentRenderId = this.getScene().getRenderId();
  19274. var worldMatrix = this._getWorldMatrix();
  19275. if (this.parent && this.parent.getWorldMatrix) {
  19276. if (!this._parentedWorldMatrix) {
  19277. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19278. }
  19279. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19280. this._markSyncedWithParent();
  19281. return this._parentedWorldMatrix;
  19282. }
  19283. return worldMatrix;
  19284. };
  19285. /**
  19286. * Sort function to order lights for rendering.
  19287. * @param a First Light object to compare to second.
  19288. * @param b Second Light object to compare first.
  19289. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19290. */
  19291. Light.CompareLightsPriority = function (a, b) {
  19292. //shadow-casting lights have priority over non-shadow-casting lights
  19293. //the renderPrioirty is a secondary sort criterion
  19294. if (a.shadowEnabled !== b.shadowEnabled) {
  19295. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19296. }
  19297. return b.renderPriority - a.renderPriority;
  19298. };
  19299. /**
  19300. * Disposes the light.
  19301. */
  19302. Light.prototype.dispose = function () {
  19303. if (this._shadowGenerator) {
  19304. this._shadowGenerator.dispose();
  19305. this._shadowGenerator = null;
  19306. }
  19307. // Animations
  19308. this.getScene().stopAnimation(this);
  19309. // Remove from meshes
  19310. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19311. var mesh = _a[_i];
  19312. mesh._removeLightSource(this);
  19313. }
  19314. this._uniformBuffer.dispose();
  19315. // Remove from scene
  19316. this.getScene().removeLight(this);
  19317. _super.prototype.dispose.call(this);
  19318. };
  19319. /**
  19320. * Returns the light type ID (integer).
  19321. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19322. */
  19323. Light.prototype.getTypeID = function () {
  19324. return 0;
  19325. };
  19326. /**
  19327. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19328. * @returns the scaled intensity in intensity mode unit
  19329. */
  19330. Light.prototype.getScaledIntensity = function () {
  19331. return this._photometricScale * this.intensity;
  19332. };
  19333. /**
  19334. * Returns a new Light object, named "name", from the current one.
  19335. * @param name The name of the cloned light
  19336. * @returns the new created light
  19337. */
  19338. Light.prototype.clone = function (name) {
  19339. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19340. if (!constructor) {
  19341. return null;
  19342. }
  19343. return BABYLON.SerializationHelper.Clone(constructor, this);
  19344. };
  19345. /**
  19346. * Serializes the current light into a Serialization object.
  19347. * @returns the serialized object.
  19348. */
  19349. Light.prototype.serialize = function () {
  19350. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19351. // Type
  19352. serializationObject.type = this.getTypeID();
  19353. // Parent
  19354. if (this.parent) {
  19355. serializationObject.parentId = this.parent.id;
  19356. }
  19357. // Inclusion / exclusions
  19358. if (this.excludedMeshes.length > 0) {
  19359. serializationObject.excludedMeshesIds = [];
  19360. this.excludedMeshes.forEach(function (mesh) {
  19361. serializationObject.excludedMeshesIds.push(mesh.id);
  19362. });
  19363. }
  19364. if (this.includedOnlyMeshes.length > 0) {
  19365. serializationObject.includedOnlyMeshesIds = [];
  19366. this.includedOnlyMeshes.forEach(function (mesh) {
  19367. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19368. });
  19369. }
  19370. // Animations
  19371. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19372. serializationObject.ranges = this.serializeAnimationRanges();
  19373. return serializationObject;
  19374. };
  19375. /**
  19376. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19377. * This new light is named "name" and added to the passed scene.
  19378. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19379. * @param name The friendly name of the light
  19380. * @param scene The scene the new light will belong to
  19381. * @returns the constructor function
  19382. */
  19383. Light.GetConstructorFromName = function (type, name, scene) {
  19384. switch (type) {
  19385. case 0:
  19386. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19387. case 1:
  19388. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19389. case 2:
  19390. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19391. case 3:
  19392. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19393. }
  19394. return null;
  19395. };
  19396. /**
  19397. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19398. * @param parsedLight The JSON representation of the light
  19399. * @param scene The scene to create the parsed light in
  19400. * @returns the created light after parsing
  19401. */
  19402. Light.Parse = function (parsedLight, scene) {
  19403. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19404. if (!constructor) {
  19405. return null;
  19406. }
  19407. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19408. // Inclusion / exclusions
  19409. if (parsedLight.excludedMeshesIds) {
  19410. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19411. }
  19412. if (parsedLight.includedOnlyMeshesIds) {
  19413. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19414. }
  19415. // Parent
  19416. if (parsedLight.parentId) {
  19417. light._waitingParentId = parsedLight.parentId;
  19418. }
  19419. // Animations
  19420. if (parsedLight.animations) {
  19421. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19422. var parsedAnimation = parsedLight.animations[animationIndex];
  19423. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19424. }
  19425. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19426. }
  19427. if (parsedLight.autoAnimate) {
  19428. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19429. }
  19430. return light;
  19431. };
  19432. Light.prototype._hookArrayForExcluded = function (array) {
  19433. var _this = this;
  19434. var oldPush = array.push;
  19435. array.push = function () {
  19436. var items = [];
  19437. for (var _i = 0; _i < arguments.length; _i++) {
  19438. items[_i] = arguments[_i];
  19439. }
  19440. var result = oldPush.apply(array, items);
  19441. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19442. var item = items_1[_a];
  19443. item._resyncLighSource(_this);
  19444. }
  19445. return result;
  19446. };
  19447. var oldSplice = array.splice;
  19448. array.splice = function (index, deleteCount) {
  19449. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19450. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19451. var item = deleted_1[_i];
  19452. item._resyncLighSource(_this);
  19453. }
  19454. return deleted;
  19455. };
  19456. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19457. var item = array_1[_i];
  19458. item._resyncLighSource(this);
  19459. }
  19460. };
  19461. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19462. var _this = this;
  19463. var oldPush = array.push;
  19464. array.push = function () {
  19465. var items = [];
  19466. for (var _i = 0; _i < arguments.length; _i++) {
  19467. items[_i] = arguments[_i];
  19468. }
  19469. var result = oldPush.apply(array, items);
  19470. _this._resyncMeshes();
  19471. return result;
  19472. };
  19473. var oldSplice = array.splice;
  19474. array.splice = function (index, deleteCount) {
  19475. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19476. _this._resyncMeshes();
  19477. return deleted;
  19478. };
  19479. this._resyncMeshes();
  19480. };
  19481. Light.prototype._resyncMeshes = function () {
  19482. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19483. var mesh = _a[_i];
  19484. mesh._resyncLighSource(this);
  19485. }
  19486. };
  19487. /**
  19488. * Forces the meshes to update their light related information in their rendering used effects
  19489. * @ignore Internal Use Only
  19490. */
  19491. Light.prototype._markMeshesAsLightDirty = function () {
  19492. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19493. var mesh = _a[_i];
  19494. if (mesh._lightSources.indexOf(this) !== -1) {
  19495. mesh._markSubMeshesAsLightDirty();
  19496. }
  19497. }
  19498. };
  19499. /**
  19500. * Recomputes the cached photometric scale if needed.
  19501. */
  19502. Light.prototype._computePhotometricScale = function () {
  19503. this._photometricScale = this._getPhotometricScale();
  19504. this.getScene().resetCachedMaterial();
  19505. };
  19506. /**
  19507. * Returns the Photometric Scale according to the light type and intensity mode.
  19508. */
  19509. Light.prototype._getPhotometricScale = function () {
  19510. var photometricScale = 0.0;
  19511. var lightTypeID = this.getTypeID();
  19512. //get photometric mode
  19513. var photometricMode = this.intensityMode;
  19514. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19515. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19516. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19517. }
  19518. else {
  19519. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19520. }
  19521. }
  19522. //compute photometric scale
  19523. switch (lightTypeID) {
  19524. case Light.LIGHTTYPEID_POINTLIGHT:
  19525. case Light.LIGHTTYPEID_SPOTLIGHT:
  19526. switch (photometricMode) {
  19527. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19528. photometricScale = 1.0 / (4.0 * Math.PI);
  19529. break;
  19530. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19531. photometricScale = 1.0;
  19532. break;
  19533. case Light.INTENSITYMODE_LUMINANCE:
  19534. photometricScale = this.radius * this.radius;
  19535. break;
  19536. }
  19537. break;
  19538. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19539. switch (photometricMode) {
  19540. case Light.INTENSITYMODE_ILLUMINANCE:
  19541. photometricScale = 1.0;
  19542. break;
  19543. case Light.INTENSITYMODE_LUMINANCE:
  19544. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19545. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19546. var apexAngleRadians = this.radius;
  19547. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19548. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19549. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19550. photometricScale = solidAngle;
  19551. break;
  19552. }
  19553. break;
  19554. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19555. // No fall off in hemisperic light.
  19556. photometricScale = 1.0;
  19557. break;
  19558. }
  19559. return photometricScale;
  19560. };
  19561. /**
  19562. * Reorder the light in the scene according to their defined priority.
  19563. * @ignore Internal Use Only
  19564. */
  19565. Light.prototype._reorderLightsInScene = function () {
  19566. var scene = this.getScene();
  19567. if (this._renderPriority != 0) {
  19568. scene.requireLightSorting = true;
  19569. }
  19570. this.getScene().sortLightsByPriority();
  19571. };
  19572. //lightmapMode Consts
  19573. Light._LIGHTMAP_DEFAULT = 0;
  19574. Light._LIGHTMAP_SPECULAR = 1;
  19575. Light._LIGHTMAP_SHADOWSONLY = 2;
  19576. // Intensity Mode Consts
  19577. Light._INTENSITYMODE_AUTOMATIC = 0;
  19578. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19579. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19580. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19581. Light._INTENSITYMODE_LUMINANCE = 4;
  19582. // Light types ids const.
  19583. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19584. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19585. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19586. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19587. __decorate([
  19588. BABYLON.serializeAsColor3()
  19589. ], Light.prototype, "diffuse", void 0);
  19590. __decorate([
  19591. BABYLON.serializeAsColor3()
  19592. ], Light.prototype, "specular", void 0);
  19593. __decorate([
  19594. BABYLON.serialize()
  19595. ], Light.prototype, "intensity", void 0);
  19596. __decorate([
  19597. BABYLON.serialize()
  19598. ], Light.prototype, "range", void 0);
  19599. __decorate([
  19600. BABYLON.serialize()
  19601. ], Light.prototype, "intensityMode", null);
  19602. __decorate([
  19603. BABYLON.serialize()
  19604. ], Light.prototype, "radius", null);
  19605. __decorate([
  19606. BABYLON.serialize()
  19607. ], Light.prototype, "_renderPriority", void 0);
  19608. __decorate([
  19609. BABYLON.expandToProperty("_reorderLightsInScene")
  19610. ], Light.prototype, "renderPriority", void 0);
  19611. __decorate([
  19612. BABYLON.serialize()
  19613. ], Light.prototype, "shadowEnabled", void 0);
  19614. __decorate([
  19615. BABYLON.serialize("excludeWithLayerMask")
  19616. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19617. __decorate([
  19618. BABYLON.serialize("includeOnlyWithLayerMask")
  19619. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19620. __decorate([
  19621. BABYLON.serialize("lightmapMode")
  19622. ], Light.prototype, "_lightmapMode", void 0);
  19623. return Light;
  19624. }(BABYLON.Node));
  19625. BABYLON.Light = Light;
  19626. })(BABYLON || (BABYLON = {}));
  19627. //# sourceMappingURL=babylon.light.js.map
  19628. var BABYLON;
  19629. (function (BABYLON) {
  19630. var Camera = /** @class */ (function (_super) {
  19631. __extends(Camera, _super);
  19632. function Camera(name, position, scene) {
  19633. var _this = _super.call(this, name, scene) || this;
  19634. /**
  19635. * The vector the camera should consider as up.
  19636. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19637. */
  19638. _this.upVector = BABYLON.Vector3.Up();
  19639. _this.orthoLeft = null;
  19640. _this.orthoRight = null;
  19641. _this.orthoBottom = null;
  19642. _this.orthoTop = null;
  19643. /**
  19644. * FOV is set in Radians. (default is 0.8)
  19645. */
  19646. _this.fov = 0.8;
  19647. _this.minZ = 1;
  19648. _this.maxZ = 10000.0;
  19649. _this.inertia = 0.9;
  19650. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19651. _this.isIntermediate = false;
  19652. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  19653. /**
  19654. * Restricts the camera to viewing objects with the same layerMask.
  19655. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  19656. */
  19657. _this.layerMask = 0x0FFFFFFF;
  19658. /**
  19659. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  19660. */
  19661. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  19662. // Camera rig members
  19663. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  19664. _this._rigCameras = new Array();
  19665. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  19666. _this._skipRendering = false;
  19667. _this.customRenderTargets = new Array();
  19668. // Observables
  19669. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  19670. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  19671. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  19672. _this.onRestoreStateObservable = new BABYLON.Observable();
  19673. // Cache
  19674. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  19675. _this._projectionMatrix = new BABYLON.Matrix();
  19676. _this._doNotComputeProjectionMatrix = false;
  19677. _this._postProcesses = new Array();
  19678. _this._transformMatrix = BABYLON.Matrix.Zero();
  19679. _this._activeMeshes = new BABYLON.SmartArray(256);
  19680. _this._globalPosition = BABYLON.Vector3.Zero();
  19681. _this._refreshFrustumPlanes = true;
  19682. _this.getScene().addCamera(_this);
  19683. if (!_this.getScene().activeCamera) {
  19684. _this.getScene().activeCamera = _this;
  19685. }
  19686. _this.position = position;
  19687. return _this;
  19688. }
  19689. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  19690. get: function () {
  19691. return Camera._PERSPECTIVE_CAMERA;
  19692. },
  19693. enumerable: true,
  19694. configurable: true
  19695. });
  19696. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  19697. get: function () {
  19698. return Camera._ORTHOGRAPHIC_CAMERA;
  19699. },
  19700. enumerable: true,
  19701. configurable: true
  19702. });
  19703. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  19704. /**
  19705. * This is the default FOV mode for perspective cameras.
  19706. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  19707. *
  19708. */
  19709. get: function () {
  19710. return Camera._FOVMODE_VERTICAL_FIXED;
  19711. },
  19712. enumerable: true,
  19713. configurable: true
  19714. });
  19715. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  19716. /**
  19717. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  19718. *
  19719. */
  19720. get: function () {
  19721. return Camera._FOVMODE_HORIZONTAL_FIXED;
  19722. },
  19723. enumerable: true,
  19724. configurable: true
  19725. });
  19726. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  19727. get: function () {
  19728. return Camera._RIG_MODE_NONE;
  19729. },
  19730. enumerable: true,
  19731. configurable: true
  19732. });
  19733. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  19734. get: function () {
  19735. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  19736. },
  19737. enumerable: true,
  19738. configurable: true
  19739. });
  19740. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  19741. get: function () {
  19742. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  19743. },
  19744. enumerable: true,
  19745. configurable: true
  19746. });
  19747. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  19748. get: function () {
  19749. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19750. },
  19751. enumerable: true,
  19752. configurable: true
  19753. });
  19754. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  19755. get: function () {
  19756. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  19757. },
  19758. enumerable: true,
  19759. configurable: true
  19760. });
  19761. Object.defineProperty(Camera, "RIG_MODE_VR", {
  19762. get: function () {
  19763. return Camera._RIG_MODE_VR;
  19764. },
  19765. enumerable: true,
  19766. configurable: true
  19767. });
  19768. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  19769. get: function () {
  19770. return Camera._RIG_MODE_WEBVR;
  19771. },
  19772. enumerable: true,
  19773. configurable: true
  19774. });
  19775. /**
  19776. * Store current camera state (fov, position, etc..)
  19777. */
  19778. Camera.prototype.storeState = function () {
  19779. this._stateStored = true;
  19780. this._storedFov = this.fov;
  19781. return this;
  19782. };
  19783. /**
  19784. * Restores the camera state values if it has been stored. You must call storeState() first
  19785. */
  19786. Camera.prototype._restoreStateValues = function () {
  19787. if (!this._stateStored) {
  19788. return false;
  19789. }
  19790. this.fov = this._storedFov;
  19791. return true;
  19792. };
  19793. /**
  19794. * Restored camera state. You must call storeState() first
  19795. */
  19796. Camera.prototype.restoreState = function () {
  19797. if (this._restoreStateValues()) {
  19798. this.onRestoreStateObservable.notifyObservers(this);
  19799. return true;
  19800. }
  19801. return false;
  19802. };
  19803. Camera.prototype.getClassName = function () {
  19804. return "Camera";
  19805. };
  19806. /**
  19807. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19808. */
  19809. Camera.prototype.toString = function (fullDetails) {
  19810. var ret = "Name: " + this.name;
  19811. ret += ", type: " + this.getClassName();
  19812. if (this.animations) {
  19813. for (var i = 0; i < this.animations.length; i++) {
  19814. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19815. }
  19816. }
  19817. if (fullDetails) {
  19818. }
  19819. return ret;
  19820. };
  19821. Object.defineProperty(Camera.prototype, "globalPosition", {
  19822. get: function () {
  19823. return this._globalPosition;
  19824. },
  19825. enumerable: true,
  19826. configurable: true
  19827. });
  19828. Camera.prototype.getActiveMeshes = function () {
  19829. return this._activeMeshes;
  19830. };
  19831. Camera.prototype.isActiveMesh = function (mesh) {
  19832. return (this._activeMeshes.indexOf(mesh) !== -1);
  19833. };
  19834. //Cache
  19835. Camera.prototype._initCache = function () {
  19836. _super.prototype._initCache.call(this);
  19837. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19838. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19839. this._cache.mode = undefined;
  19840. this._cache.minZ = undefined;
  19841. this._cache.maxZ = undefined;
  19842. this._cache.fov = undefined;
  19843. this._cache.fovMode = undefined;
  19844. this._cache.aspectRatio = undefined;
  19845. this._cache.orthoLeft = undefined;
  19846. this._cache.orthoRight = undefined;
  19847. this._cache.orthoBottom = undefined;
  19848. this._cache.orthoTop = undefined;
  19849. this._cache.renderWidth = undefined;
  19850. this._cache.renderHeight = undefined;
  19851. };
  19852. Camera.prototype._updateCache = function (ignoreParentClass) {
  19853. if (!ignoreParentClass) {
  19854. _super.prototype._updateCache.call(this);
  19855. }
  19856. this._cache.position.copyFrom(this.position);
  19857. this._cache.upVector.copyFrom(this.upVector);
  19858. };
  19859. // Synchronized
  19860. Camera.prototype._isSynchronized = function () {
  19861. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  19862. };
  19863. Camera.prototype._isSynchronizedViewMatrix = function () {
  19864. if (!_super.prototype._isSynchronized.call(this))
  19865. return false;
  19866. return this._cache.position.equals(this.position)
  19867. && this._cache.upVector.equals(this.upVector)
  19868. && this.isSynchronizedWithParent();
  19869. };
  19870. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  19871. var check = this._cache.mode === this.mode
  19872. && this._cache.minZ === this.minZ
  19873. && this._cache.maxZ === this.maxZ;
  19874. if (!check) {
  19875. return false;
  19876. }
  19877. var engine = this.getEngine();
  19878. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19879. check = this._cache.fov === this.fov
  19880. && this._cache.fovMode === this.fovMode
  19881. && this._cache.aspectRatio === engine.getAspectRatio(this);
  19882. }
  19883. else {
  19884. check = this._cache.orthoLeft === this.orthoLeft
  19885. && this._cache.orthoRight === this.orthoRight
  19886. && this._cache.orthoBottom === this.orthoBottom
  19887. && this._cache.orthoTop === this.orthoTop
  19888. && this._cache.renderWidth === engine.getRenderWidth()
  19889. && this._cache.renderHeight === engine.getRenderHeight();
  19890. }
  19891. return check;
  19892. };
  19893. // Controls
  19894. Camera.prototype.attachControl = function (element, noPreventDefault) {
  19895. };
  19896. Camera.prototype.detachControl = function (element) {
  19897. };
  19898. Camera.prototype.update = function () {
  19899. this._checkInputs();
  19900. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19901. this._updateRigCameras();
  19902. }
  19903. };
  19904. Camera.prototype._checkInputs = function () {
  19905. this.onAfterCheckInputsObservable.notifyObservers(this);
  19906. };
  19907. Object.defineProperty(Camera.prototype, "rigCameras", {
  19908. get: function () {
  19909. return this._rigCameras;
  19910. },
  19911. enumerable: true,
  19912. configurable: true
  19913. });
  19914. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  19915. get: function () {
  19916. return this._rigPostProcess;
  19917. },
  19918. enumerable: true,
  19919. configurable: true
  19920. });
  19921. Camera.prototype._cascadePostProcessesToRigCams = function () {
  19922. // invalidate framebuffer
  19923. if (this._postProcesses.length > 0) {
  19924. this._postProcesses[0].markTextureDirty();
  19925. }
  19926. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  19927. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  19928. var cam = this._rigCameras[i];
  19929. var rigPostProcess = cam._rigPostProcess;
  19930. // for VR rig, there does not have to be a post process
  19931. if (rigPostProcess) {
  19932. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  19933. if (isPass) {
  19934. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  19935. cam.isIntermediate = this._postProcesses.length === 0;
  19936. }
  19937. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  19938. rigPostProcess.markTextureDirty();
  19939. }
  19940. else {
  19941. cam._postProcesses = this._postProcesses.slice(0);
  19942. }
  19943. }
  19944. };
  19945. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  19946. if (insertAt === void 0) { insertAt = null; }
  19947. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  19948. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  19949. return 0;
  19950. }
  19951. if (insertAt == null || insertAt < 0) {
  19952. this._postProcesses.push(postProcess);
  19953. }
  19954. else {
  19955. this._postProcesses.splice(insertAt, 0, postProcess);
  19956. }
  19957. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19958. return this._postProcesses.indexOf(postProcess);
  19959. };
  19960. Camera.prototype.detachPostProcess = function (postProcess) {
  19961. var idx = this._postProcesses.indexOf(postProcess);
  19962. if (idx !== -1) {
  19963. this._postProcesses.splice(idx, 1);
  19964. }
  19965. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19966. };
  19967. Camera.prototype.getWorldMatrix = function () {
  19968. if (!this._worldMatrix) {
  19969. this._worldMatrix = BABYLON.Matrix.Identity();
  19970. }
  19971. var viewMatrix = this.getViewMatrix();
  19972. viewMatrix.invertToRef(this._worldMatrix);
  19973. return this._worldMatrix;
  19974. };
  19975. Camera.prototype._getViewMatrix = function () {
  19976. return BABYLON.Matrix.Identity();
  19977. };
  19978. Camera.prototype.getViewMatrix = function (force) {
  19979. if (!force && this._isSynchronizedViewMatrix()) {
  19980. return this._computedViewMatrix;
  19981. }
  19982. this.updateCache();
  19983. this._computedViewMatrix = this._getViewMatrix();
  19984. this._currentRenderId = this.getScene().getRenderId();
  19985. this._refreshFrustumPlanes = true;
  19986. if (!this.parent || !this.parent.getWorldMatrix) {
  19987. this._globalPosition.copyFrom(this.position);
  19988. }
  19989. else {
  19990. if (!this._worldMatrix) {
  19991. this._worldMatrix = BABYLON.Matrix.Identity();
  19992. }
  19993. this._computedViewMatrix.invertToRef(this._worldMatrix);
  19994. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  19995. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  19996. this._computedViewMatrix.invert();
  19997. this._markSyncedWithParent();
  19998. }
  19999. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20000. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20001. }
  20002. this.onViewMatrixChangedObservable.notifyObservers(this);
  20003. return this._computedViewMatrix;
  20004. };
  20005. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20006. this._doNotComputeProjectionMatrix = true;
  20007. if (projection !== undefined) {
  20008. this._projectionMatrix = projection;
  20009. }
  20010. };
  20011. ;
  20012. Camera.prototype.unfreezeProjectionMatrix = function () {
  20013. this._doNotComputeProjectionMatrix = false;
  20014. };
  20015. ;
  20016. Camera.prototype.getProjectionMatrix = function (force) {
  20017. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20018. return this._projectionMatrix;
  20019. }
  20020. // Cache
  20021. this._cache.mode = this.mode;
  20022. this._cache.minZ = this.minZ;
  20023. this._cache.maxZ = this.maxZ;
  20024. // Matrix
  20025. this._refreshFrustumPlanes = true;
  20026. var engine = this.getEngine();
  20027. var scene = this.getScene();
  20028. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20029. this._cache.fov = this.fov;
  20030. this._cache.fovMode = this.fovMode;
  20031. this._cache.aspectRatio = engine.getAspectRatio(this);
  20032. if (this.minZ <= 0) {
  20033. this.minZ = 0.1;
  20034. }
  20035. if (scene.useRightHandedSystem) {
  20036. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20037. }
  20038. else {
  20039. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20040. }
  20041. }
  20042. else {
  20043. var halfWidth = engine.getRenderWidth() / 2.0;
  20044. var halfHeight = engine.getRenderHeight() / 2.0;
  20045. if (scene.useRightHandedSystem) {
  20046. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20047. }
  20048. else {
  20049. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20050. }
  20051. this._cache.orthoLeft = this.orthoLeft;
  20052. this._cache.orthoRight = this.orthoRight;
  20053. this._cache.orthoBottom = this.orthoBottom;
  20054. this._cache.orthoTop = this.orthoTop;
  20055. this._cache.renderWidth = engine.getRenderWidth();
  20056. this._cache.renderHeight = engine.getRenderHeight();
  20057. }
  20058. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20059. return this._projectionMatrix;
  20060. };
  20061. Camera.prototype.getTranformationMatrix = function () {
  20062. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20063. return this._transformMatrix;
  20064. };
  20065. Camera.prototype.updateFrustumPlanes = function () {
  20066. if (!this._refreshFrustumPlanes) {
  20067. return;
  20068. }
  20069. this.getTranformationMatrix();
  20070. if (!this._frustumPlanes) {
  20071. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20072. }
  20073. else {
  20074. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20075. }
  20076. this._refreshFrustumPlanes = false;
  20077. };
  20078. Camera.prototype.isInFrustum = function (target) {
  20079. this.updateFrustumPlanes();
  20080. return target.isInFrustum(this._frustumPlanes);
  20081. };
  20082. Camera.prototype.isCompletelyInFrustum = function (target) {
  20083. this.updateFrustumPlanes();
  20084. return target.isCompletelyInFrustum(this._frustumPlanes);
  20085. };
  20086. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20087. if (length === void 0) { length = 100; }
  20088. if (!transform) {
  20089. transform = this.getWorldMatrix();
  20090. }
  20091. if (!origin) {
  20092. origin = this.position;
  20093. }
  20094. var forward = new BABYLON.Vector3(0, 0, 1);
  20095. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20096. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20097. return new BABYLON.Ray(origin, direction, length);
  20098. };
  20099. Camera.prototype.dispose = function () {
  20100. // Observables
  20101. this.onViewMatrixChangedObservable.clear();
  20102. this.onProjectionMatrixChangedObservable.clear();
  20103. this.onAfterCheckInputsObservable.clear();
  20104. this.onRestoreStateObservable.clear();
  20105. // Inputs
  20106. if (this.inputs) {
  20107. this.inputs.clear();
  20108. }
  20109. // Animations
  20110. this.getScene().stopAnimation(this);
  20111. // Remove from scene
  20112. this.getScene().removeCamera(this);
  20113. while (this._rigCameras.length > 0) {
  20114. var camera = this._rigCameras.pop();
  20115. if (camera) {
  20116. camera.dispose();
  20117. }
  20118. }
  20119. // Postprocesses
  20120. if (this._rigPostProcess) {
  20121. this._rigPostProcess.dispose(this);
  20122. this._rigPostProcess = null;
  20123. this._postProcesses = [];
  20124. }
  20125. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20126. this._rigPostProcess = null;
  20127. this._postProcesses = [];
  20128. }
  20129. else {
  20130. var i = this._postProcesses.length;
  20131. while (--i >= 0) {
  20132. this._postProcesses[i].dispose(this);
  20133. }
  20134. }
  20135. // Render targets
  20136. var i = this.customRenderTargets.length;
  20137. while (--i >= 0) {
  20138. this.customRenderTargets[i].dispose();
  20139. }
  20140. this.customRenderTargets = [];
  20141. // Active Meshes
  20142. this._activeMeshes.dispose();
  20143. _super.prototype.dispose.call(this);
  20144. };
  20145. Object.defineProperty(Camera.prototype, "leftCamera", {
  20146. // ---- Camera rigs section ----
  20147. get: function () {
  20148. if (this._rigCameras.length < 1) {
  20149. return null;
  20150. }
  20151. return this._rigCameras[0];
  20152. },
  20153. enumerable: true,
  20154. configurable: true
  20155. });
  20156. Object.defineProperty(Camera.prototype, "rightCamera", {
  20157. get: function () {
  20158. if (this._rigCameras.length < 2) {
  20159. return null;
  20160. }
  20161. return this._rigCameras[1];
  20162. },
  20163. enumerable: true,
  20164. configurable: true
  20165. });
  20166. Camera.prototype.getLeftTarget = function () {
  20167. if (this._rigCameras.length < 1) {
  20168. return null;
  20169. }
  20170. return this._rigCameras[0].getTarget();
  20171. };
  20172. Camera.prototype.getRightTarget = function () {
  20173. if (this._rigCameras.length < 2) {
  20174. return null;
  20175. }
  20176. return this._rigCameras[1].getTarget();
  20177. };
  20178. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20179. if (this.cameraRigMode === mode) {
  20180. return;
  20181. }
  20182. while (this._rigCameras.length > 0) {
  20183. var camera = this._rigCameras.pop();
  20184. if (camera) {
  20185. camera.dispose();
  20186. }
  20187. }
  20188. this.cameraRigMode = mode;
  20189. this._cameraRigParams = {};
  20190. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20191. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20192. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20193. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20194. // create the rig cameras, unless none
  20195. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20196. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20197. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20198. if (leftCamera && rightCamera) {
  20199. this._rigCameras.push(leftCamera);
  20200. this._rigCameras.push(rightCamera);
  20201. }
  20202. }
  20203. switch (this.cameraRigMode) {
  20204. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20205. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20206. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20207. break;
  20208. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20209. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20210. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20211. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20212. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20213. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20214. break;
  20215. case Camera.RIG_MODE_VR:
  20216. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20217. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20218. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20219. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20220. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20221. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20222. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20223. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20224. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20225. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20226. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20227. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20228. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20229. if (metrics.compensateDistortion) {
  20230. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20231. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20232. }
  20233. break;
  20234. case Camera.RIG_MODE_WEBVR:
  20235. if (rigParams.vrDisplay) {
  20236. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20237. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20238. //Left eye
  20239. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20240. this._rigCameras[0].setCameraRigParameter("left", true);
  20241. //leaving this for future reference
  20242. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20243. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20244. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20245. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20246. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20247. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20248. this._rigCameras[0].parent = this;
  20249. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20250. //Right eye
  20251. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20252. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20253. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20254. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20255. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20256. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20257. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20258. this._rigCameras[1].parent = this;
  20259. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20260. if (Camera.UseAlternateWebVRRendering) {
  20261. this._rigCameras[1]._skipRendering = true;
  20262. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20263. }
  20264. }
  20265. break;
  20266. }
  20267. this._cascadePostProcessesToRigCams();
  20268. this.update();
  20269. };
  20270. Camera.prototype._getVRProjectionMatrix = function () {
  20271. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20272. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20273. return this._projectionMatrix;
  20274. };
  20275. Camera.prototype._updateCameraRotationMatrix = function () {
  20276. //Here for WebVR
  20277. };
  20278. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20279. //Here for WebVR
  20280. };
  20281. /**
  20282. * This function MUST be overwritten by the different WebVR cameras available.
  20283. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20284. */
  20285. Camera.prototype._getWebVRProjectionMatrix = function () {
  20286. return BABYLON.Matrix.Identity();
  20287. };
  20288. /**
  20289. * This function MUST be overwritten by the different WebVR cameras available.
  20290. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20291. */
  20292. Camera.prototype._getWebVRViewMatrix = function () {
  20293. return BABYLON.Matrix.Identity();
  20294. };
  20295. Camera.prototype.setCameraRigParameter = function (name, value) {
  20296. if (!this._cameraRigParams) {
  20297. this._cameraRigParams = {};
  20298. }
  20299. this._cameraRigParams[name] = value;
  20300. //provisionnally:
  20301. if (name === "interaxialDistance") {
  20302. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20303. }
  20304. };
  20305. /**
  20306. * needs to be overridden by children so sub has required properties to be copied
  20307. */
  20308. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20309. return null;
  20310. };
  20311. /**
  20312. * May need to be overridden by children
  20313. */
  20314. Camera.prototype._updateRigCameras = function () {
  20315. for (var i = 0; i < this._rigCameras.length; i++) {
  20316. this._rigCameras[i].minZ = this.minZ;
  20317. this._rigCameras[i].maxZ = this.maxZ;
  20318. this._rigCameras[i].fov = this.fov;
  20319. }
  20320. // only update viewport when ANAGLYPH
  20321. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20322. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20323. }
  20324. };
  20325. Camera.prototype._setupInputs = function () {
  20326. };
  20327. Camera.prototype.serialize = function () {
  20328. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20329. // Type
  20330. serializationObject.type = this.getClassName();
  20331. // Parent
  20332. if (this.parent) {
  20333. serializationObject.parentId = this.parent.id;
  20334. }
  20335. if (this.inputs) {
  20336. this.inputs.serialize(serializationObject);
  20337. }
  20338. // Animations
  20339. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20340. serializationObject.ranges = this.serializeAnimationRanges();
  20341. return serializationObject;
  20342. };
  20343. Camera.prototype.clone = function (name) {
  20344. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20345. };
  20346. Camera.prototype.getDirection = function (localAxis) {
  20347. var result = BABYLON.Vector3.Zero();
  20348. this.getDirectionToRef(localAxis, result);
  20349. return result;
  20350. };
  20351. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20352. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20353. };
  20354. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20355. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20356. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20357. switch (type) {
  20358. case "ArcRotateCamera":
  20359. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20360. case "DeviceOrientationCamera":
  20361. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20362. case "FollowCamera":
  20363. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20364. case "ArcFollowCamera":
  20365. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20366. case "GamepadCamera":
  20367. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20368. case "TouchCamera":
  20369. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20370. case "VirtualJoysticksCamera":
  20371. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20372. case "WebVRFreeCamera":
  20373. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20374. case "WebVRGamepadCamera":
  20375. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20376. case "VRDeviceOrientationFreeCamera":
  20377. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20378. case "VRDeviceOrientationGamepadCamera":
  20379. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20380. case "AnaglyphArcRotateCamera":
  20381. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20382. case "AnaglyphFreeCamera":
  20383. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20384. case "AnaglyphGamepadCamera":
  20385. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20386. case "AnaglyphUniversalCamera":
  20387. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20388. case "StereoscopicArcRotateCamera":
  20389. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20390. case "StereoscopicFreeCamera":
  20391. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20392. case "StereoscopicGamepadCamera":
  20393. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20394. case "StereoscopicUniversalCamera":
  20395. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20396. case "FreeCamera":// Forcing Universal here
  20397. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20398. default:// Universal Camera is the default value
  20399. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20400. }
  20401. };
  20402. Camera.prototype.computeWorldMatrix = function () {
  20403. return this.getWorldMatrix();
  20404. };
  20405. Camera.Parse = function (parsedCamera, scene) {
  20406. var type = parsedCamera.type;
  20407. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20408. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20409. // Parent
  20410. if (parsedCamera.parentId) {
  20411. camera._waitingParentId = parsedCamera.parentId;
  20412. }
  20413. //If camera has an input manager, let it parse inputs settings
  20414. if (camera.inputs) {
  20415. camera.inputs.parse(parsedCamera);
  20416. camera._setupInputs();
  20417. }
  20418. if (camera.setPosition) {
  20419. camera.position.copyFromFloats(0, 0, 0);
  20420. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20421. }
  20422. // Target
  20423. if (parsedCamera.target) {
  20424. if (camera.setTarget) {
  20425. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20426. }
  20427. }
  20428. // Apply 3d rig, when found
  20429. if (parsedCamera.cameraRigMode) {
  20430. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20431. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20432. }
  20433. // Animations
  20434. if (parsedCamera.animations) {
  20435. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20436. var parsedAnimation = parsedCamera.animations[animationIndex];
  20437. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20438. }
  20439. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20440. }
  20441. if (parsedCamera.autoAnimate) {
  20442. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20443. }
  20444. return camera;
  20445. };
  20446. // Statics
  20447. Camera._PERSPECTIVE_CAMERA = 0;
  20448. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20449. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20450. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20451. Camera._RIG_MODE_NONE = 0;
  20452. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20453. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20454. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20455. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20456. Camera._RIG_MODE_VR = 20;
  20457. Camera._RIG_MODE_WEBVR = 21;
  20458. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20459. Camera.UseAlternateWebVRRendering = false;
  20460. __decorate([
  20461. BABYLON.serializeAsVector3()
  20462. ], Camera.prototype, "position", void 0);
  20463. __decorate([
  20464. BABYLON.serializeAsVector3()
  20465. ], Camera.prototype, "upVector", void 0);
  20466. __decorate([
  20467. BABYLON.serialize()
  20468. ], Camera.prototype, "orthoLeft", void 0);
  20469. __decorate([
  20470. BABYLON.serialize()
  20471. ], Camera.prototype, "orthoRight", void 0);
  20472. __decorate([
  20473. BABYLON.serialize()
  20474. ], Camera.prototype, "orthoBottom", void 0);
  20475. __decorate([
  20476. BABYLON.serialize()
  20477. ], Camera.prototype, "orthoTop", void 0);
  20478. __decorate([
  20479. BABYLON.serialize()
  20480. ], Camera.prototype, "fov", void 0);
  20481. __decorate([
  20482. BABYLON.serialize()
  20483. ], Camera.prototype, "minZ", void 0);
  20484. __decorate([
  20485. BABYLON.serialize()
  20486. ], Camera.prototype, "maxZ", void 0);
  20487. __decorate([
  20488. BABYLON.serialize()
  20489. ], Camera.prototype, "inertia", void 0);
  20490. __decorate([
  20491. BABYLON.serialize()
  20492. ], Camera.prototype, "mode", void 0);
  20493. __decorate([
  20494. BABYLON.serialize()
  20495. ], Camera.prototype, "layerMask", void 0);
  20496. __decorate([
  20497. BABYLON.serialize()
  20498. ], Camera.prototype, "fovMode", void 0);
  20499. __decorate([
  20500. BABYLON.serialize()
  20501. ], Camera.prototype, "cameraRigMode", void 0);
  20502. __decorate([
  20503. BABYLON.serialize()
  20504. ], Camera.prototype, "interaxialDistance", void 0);
  20505. __decorate([
  20506. BABYLON.serialize()
  20507. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20508. return Camera;
  20509. }(BABYLON.Node));
  20510. BABYLON.Camera = Camera;
  20511. })(BABYLON || (BABYLON = {}));
  20512. //# sourceMappingURL=babylon.camera.js.map
  20513. var BABYLON;
  20514. (function (BABYLON) {
  20515. var RenderingManager = /** @class */ (function () {
  20516. function RenderingManager(scene) {
  20517. this._renderingGroups = new Array();
  20518. this._autoClearDepthStencil = {};
  20519. this._customOpaqueSortCompareFn = {};
  20520. this._customAlphaTestSortCompareFn = {};
  20521. this._customTransparentSortCompareFn = {};
  20522. this._renderinGroupInfo = null;
  20523. this._scene = scene;
  20524. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20525. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20526. }
  20527. }
  20528. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20529. if (depth === void 0) { depth = true; }
  20530. if (stencil === void 0) { stencil = true; }
  20531. if (this._depthStencilBufferAlreadyCleaned) {
  20532. return;
  20533. }
  20534. this._scene.getEngine().clear(null, false, depth, stencil);
  20535. this._depthStencilBufferAlreadyCleaned = true;
  20536. };
  20537. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20538. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20539. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20540. var info = null;
  20541. if (observable) {
  20542. if (!this._renderinGroupInfo) {
  20543. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20544. }
  20545. info = this._renderinGroupInfo;
  20546. info.scene = this._scene;
  20547. info.camera = this._scene.activeCamera;
  20548. }
  20549. // Dispatch sprites
  20550. if (renderSprites) {
  20551. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20552. var manager = this._scene.spriteManagers[index];
  20553. this.dispatchSprites(manager);
  20554. }
  20555. }
  20556. // Render
  20557. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20558. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20559. var renderingGroup = this._renderingGroups[index];
  20560. if (!renderingGroup && !observable)
  20561. continue;
  20562. var renderingGroupMask = 0;
  20563. // Fire PRECLEAR stage
  20564. if (observable && info) {
  20565. renderingGroupMask = Math.pow(2, index);
  20566. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20567. info.renderingGroupId = index;
  20568. observable.notifyObservers(info, renderingGroupMask);
  20569. }
  20570. // Clear depth/stencil if needed
  20571. if (RenderingManager.AUTOCLEAR) {
  20572. var autoClear = this._autoClearDepthStencil[index];
  20573. if (autoClear && autoClear.autoClear) {
  20574. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20575. }
  20576. }
  20577. if (observable && info) {
  20578. // Fire PREOPAQUE stage
  20579. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20580. observable.notifyObservers(info, renderingGroupMask);
  20581. // Fire PRETRANSPARENT stage
  20582. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20583. observable.notifyObservers(info, renderingGroupMask);
  20584. }
  20585. if (renderingGroup)
  20586. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20587. // Fire POSTTRANSPARENT stage
  20588. if (observable && info) {
  20589. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20590. observable.notifyObservers(info, renderingGroupMask);
  20591. }
  20592. }
  20593. };
  20594. RenderingManager.prototype.reset = function () {
  20595. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20596. var renderingGroup = this._renderingGroups[index];
  20597. if (renderingGroup) {
  20598. renderingGroup.prepare();
  20599. }
  20600. }
  20601. };
  20602. RenderingManager.prototype.dispose = function () {
  20603. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20604. var renderingGroup = this._renderingGroups[index];
  20605. if (renderingGroup) {
  20606. renderingGroup.dispose();
  20607. }
  20608. }
  20609. this._renderingGroups.length = 0;
  20610. };
  20611. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20612. if (this._renderingGroups[renderingGroupId] === undefined) {
  20613. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20614. }
  20615. };
  20616. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20617. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20618. this._prepareRenderingGroup(renderingGroupId);
  20619. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20620. };
  20621. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  20622. var renderingGroupId = particleSystem.renderingGroupId || 0;
  20623. this._prepareRenderingGroup(renderingGroupId);
  20624. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  20625. };
  20626. /**
  20627. * @param subMesh The submesh to dispatch
  20628. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20629. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20630. */
  20631. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  20632. if (mesh === undefined) {
  20633. mesh = subMesh.getMesh();
  20634. }
  20635. var renderingGroupId = mesh.renderingGroupId || 0;
  20636. this._prepareRenderingGroup(renderingGroupId);
  20637. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  20638. };
  20639. /**
  20640. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20641. * This allowed control for front to back rendering or reversly depending of the special needs.
  20642. *
  20643. * @param renderingGroupId The rendering group id corresponding to its index
  20644. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20645. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20646. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20647. */
  20648. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20649. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20650. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20651. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20652. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  20653. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  20654. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  20655. if (this._renderingGroups[renderingGroupId]) {
  20656. var group = this._renderingGroups[renderingGroupId];
  20657. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  20658. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  20659. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  20660. }
  20661. };
  20662. /**
  20663. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20664. *
  20665. * @param renderingGroupId The rendering group id corresponding to its index
  20666. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20667. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20668. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20669. */
  20670. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20671. if (depth === void 0) { depth = true; }
  20672. if (stencil === void 0) { stencil = true; }
  20673. this._autoClearDepthStencil[renderingGroupId] = {
  20674. autoClear: autoClearDepthStencil,
  20675. depth: depth,
  20676. stencil: stencil
  20677. };
  20678. };
  20679. /**
  20680. * The max id used for rendering groups (not included)
  20681. */
  20682. RenderingManager.MAX_RENDERINGGROUPS = 4;
  20683. /**
  20684. * The min id used for rendering groups (included)
  20685. */
  20686. RenderingManager.MIN_RENDERINGGROUPS = 0;
  20687. /**
  20688. * Used to globally prevent autoclearing scenes.
  20689. */
  20690. RenderingManager.AUTOCLEAR = true;
  20691. return RenderingManager;
  20692. }());
  20693. BABYLON.RenderingManager = RenderingManager;
  20694. })(BABYLON || (BABYLON = {}));
  20695. //# sourceMappingURL=babylon.renderingManager.js.map
  20696. var BABYLON;
  20697. (function (BABYLON) {
  20698. var RenderingGroup = /** @class */ (function () {
  20699. /**
  20700. * Creates a new rendering group.
  20701. * @param index The rendering group index
  20702. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  20703. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  20704. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  20705. */
  20706. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20707. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20708. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20709. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20710. this.index = index;
  20711. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  20712. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  20713. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  20714. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  20715. this._particleSystems = new BABYLON.SmartArray(256);
  20716. this._spriteManagers = new BABYLON.SmartArray(256);
  20717. this._edgesRenderers = new BABYLON.SmartArray(16);
  20718. this._scene = scene;
  20719. this.opaqueSortCompareFn = opaqueSortCompareFn;
  20720. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  20721. this.transparentSortCompareFn = transparentSortCompareFn;
  20722. }
  20723. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  20724. /**
  20725. * Set the opaque sort comparison function.
  20726. * If null the sub meshes will be render in the order they were created
  20727. */
  20728. set: function (value) {
  20729. this._opaqueSortCompareFn = value;
  20730. if (value) {
  20731. this._renderOpaque = this.renderOpaqueSorted;
  20732. }
  20733. else {
  20734. this._renderOpaque = RenderingGroup.renderUnsorted;
  20735. }
  20736. },
  20737. enumerable: true,
  20738. configurable: true
  20739. });
  20740. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  20741. /**
  20742. * Set the alpha test sort comparison function.
  20743. * If null the sub meshes will be render in the order they were created
  20744. */
  20745. set: function (value) {
  20746. this._alphaTestSortCompareFn = value;
  20747. if (value) {
  20748. this._renderAlphaTest = this.renderAlphaTestSorted;
  20749. }
  20750. else {
  20751. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  20752. }
  20753. },
  20754. enumerable: true,
  20755. configurable: true
  20756. });
  20757. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  20758. /**
  20759. * Set the transparent sort comparison function.
  20760. * If null the sub meshes will be render in the order they were created
  20761. */
  20762. set: function (value) {
  20763. if (value) {
  20764. this._transparentSortCompareFn = value;
  20765. }
  20766. else {
  20767. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  20768. }
  20769. this._renderTransparent = this.renderTransparentSorted;
  20770. },
  20771. enumerable: true,
  20772. configurable: true
  20773. });
  20774. /**
  20775. * Render all the sub meshes contained in the group.
  20776. * @param customRenderFunction Used to override the default render behaviour of the group.
  20777. * @returns true if rendered some submeshes.
  20778. */
  20779. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  20780. if (customRenderFunction) {
  20781. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  20782. return;
  20783. }
  20784. var engine = this._scene.getEngine();
  20785. // Depth only
  20786. if (this._depthOnlySubMeshes.length !== 0) {
  20787. engine.setColorWrite(false);
  20788. this._renderAlphaTest(this._depthOnlySubMeshes);
  20789. engine.setColorWrite(true);
  20790. }
  20791. // Opaque
  20792. if (this._opaqueSubMeshes.length !== 0) {
  20793. this._renderOpaque(this._opaqueSubMeshes);
  20794. }
  20795. // Alpha test
  20796. if (this._alphaTestSubMeshes.length !== 0) {
  20797. this._renderAlphaTest(this._alphaTestSubMeshes);
  20798. }
  20799. var stencilState = engine.getStencilBuffer();
  20800. engine.setStencilBuffer(false);
  20801. // Sprites
  20802. if (renderSprites) {
  20803. this._renderSprites();
  20804. }
  20805. // Particles
  20806. if (renderParticles) {
  20807. this._renderParticles(activeMeshes);
  20808. }
  20809. if (this.onBeforeTransparentRendering) {
  20810. this.onBeforeTransparentRendering();
  20811. }
  20812. // Transparent
  20813. if (this._transparentSubMeshes.length !== 0) {
  20814. this._renderTransparent(this._transparentSubMeshes);
  20815. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20816. }
  20817. // Set back stencil to false in case it changes before the edge renderer.
  20818. engine.setStencilBuffer(false);
  20819. // Edges
  20820. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  20821. this._edgesRenderers.data[edgesRendererIndex].render();
  20822. }
  20823. // Restore Stencil state.
  20824. engine.setStencilBuffer(stencilState);
  20825. };
  20826. /**
  20827. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  20828. * @param subMeshes The submeshes to render
  20829. */
  20830. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  20831. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  20832. };
  20833. /**
  20834. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  20835. * @param subMeshes The submeshes to render
  20836. */
  20837. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  20838. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  20839. };
  20840. /**
  20841. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  20842. * @param subMeshes The submeshes to render
  20843. */
  20844. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  20845. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  20846. };
  20847. /**
  20848. * Renders the submeshes in a specified order.
  20849. * @param subMeshes The submeshes to sort before render
  20850. * @param sortCompareFn The comparison function use to sort
  20851. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  20852. * @param transparent Specifies to activate blending if true
  20853. */
  20854. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  20855. var subIndex = 0;
  20856. var subMesh;
  20857. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  20858. for (; subIndex < subMeshes.length; subIndex++) {
  20859. subMesh = subMeshes.data[subIndex];
  20860. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  20861. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  20862. }
  20863. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  20864. if (sortCompareFn) {
  20865. sortedArray.sort(sortCompareFn);
  20866. }
  20867. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  20868. subMesh = sortedArray[subIndex];
  20869. if (transparent) {
  20870. var material = subMesh.getMaterial();
  20871. if (material && material.needDepthPrePass) {
  20872. var engine = material.getScene().getEngine();
  20873. engine.setColorWrite(false);
  20874. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20875. subMesh.render(false);
  20876. engine.setColorWrite(true);
  20877. }
  20878. }
  20879. subMesh.render(transparent);
  20880. }
  20881. };
  20882. /**
  20883. * Renders the submeshes in the order they were dispatched (no sort applied).
  20884. * @param subMeshes The submeshes to render
  20885. */
  20886. RenderingGroup.renderUnsorted = function (subMeshes) {
  20887. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  20888. var submesh = subMeshes.data[subIndex];
  20889. submesh.render(false);
  20890. }
  20891. };
  20892. /**
  20893. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20894. * are rendered back to front if in the same alpha index.
  20895. *
  20896. * @param a The first submesh
  20897. * @param b The second submesh
  20898. * @returns The result of the comparison
  20899. */
  20900. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  20901. // Alpha index first
  20902. if (a._alphaIndex > b._alphaIndex) {
  20903. return 1;
  20904. }
  20905. if (a._alphaIndex < b._alphaIndex) {
  20906. return -1;
  20907. }
  20908. // Then distance to camera
  20909. return RenderingGroup.backToFrontSortCompare(a, b);
  20910. };
  20911. /**
  20912. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20913. * are rendered back to front.
  20914. *
  20915. * @param a The first submesh
  20916. * @param b The second submesh
  20917. * @returns The result of the comparison
  20918. */
  20919. RenderingGroup.backToFrontSortCompare = function (a, b) {
  20920. // Then distance to camera
  20921. if (a._distanceToCamera < b._distanceToCamera) {
  20922. return 1;
  20923. }
  20924. if (a._distanceToCamera > b._distanceToCamera) {
  20925. return -1;
  20926. }
  20927. return 0;
  20928. };
  20929. /**
  20930. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20931. * are rendered front to back (prevent overdraw).
  20932. *
  20933. * @param a The first submesh
  20934. * @param b The second submesh
  20935. * @returns The result of the comparison
  20936. */
  20937. RenderingGroup.frontToBackSortCompare = function (a, b) {
  20938. // Then distance to camera
  20939. if (a._distanceToCamera < b._distanceToCamera) {
  20940. return -1;
  20941. }
  20942. if (a._distanceToCamera > b._distanceToCamera) {
  20943. return 1;
  20944. }
  20945. return 0;
  20946. };
  20947. /**
  20948. * Resets the different lists of submeshes to prepare a new frame.
  20949. */
  20950. RenderingGroup.prototype.prepare = function () {
  20951. this._opaqueSubMeshes.reset();
  20952. this._transparentSubMeshes.reset();
  20953. this._alphaTestSubMeshes.reset();
  20954. this._depthOnlySubMeshes.reset();
  20955. this._particleSystems.reset();
  20956. this._spriteManagers.reset();
  20957. this._edgesRenderers.reset();
  20958. };
  20959. RenderingGroup.prototype.dispose = function () {
  20960. this._opaqueSubMeshes.dispose();
  20961. this._transparentSubMeshes.dispose();
  20962. this._alphaTestSubMeshes.dispose();
  20963. this._depthOnlySubMeshes.dispose();
  20964. this._particleSystems.dispose();
  20965. this._spriteManagers.dispose();
  20966. this._edgesRenderers.dispose();
  20967. };
  20968. /**
  20969. * Inserts the submesh in its correct queue depending on its material.
  20970. * @param subMesh The submesh to dispatch
  20971. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20972. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20973. */
  20974. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  20975. // Get mesh and materials if not provided
  20976. if (mesh === undefined) {
  20977. mesh = subMesh.getMesh();
  20978. }
  20979. if (material === undefined) {
  20980. material = subMesh.getMaterial();
  20981. }
  20982. if (material === null || material === undefined) {
  20983. return;
  20984. }
  20985. if (material.needAlphaBlendingForMesh(mesh)) {
  20986. this._transparentSubMeshes.push(subMesh);
  20987. }
  20988. else if (material.needAlphaTesting()) {
  20989. if (material.needDepthPrePass) {
  20990. this._depthOnlySubMeshes.push(subMesh);
  20991. }
  20992. this._alphaTestSubMeshes.push(subMesh);
  20993. }
  20994. else {
  20995. if (material.needDepthPrePass) {
  20996. this._depthOnlySubMeshes.push(subMesh);
  20997. }
  20998. this._opaqueSubMeshes.push(subMesh); // Opaque
  20999. }
  21000. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21001. this._edgesRenderers.push(mesh._edgesRenderer);
  21002. }
  21003. };
  21004. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21005. this._spriteManagers.push(spriteManager);
  21006. };
  21007. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21008. this._particleSystems.push(particleSystem);
  21009. };
  21010. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21011. if (this._particleSystems.length === 0) {
  21012. return;
  21013. }
  21014. // Particles
  21015. var activeCamera = this._scene.activeCamera;
  21016. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21017. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21018. var particleSystem = this._particleSystems.data[particleIndex];
  21019. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21020. continue;
  21021. }
  21022. var emitter = particleSystem.emitter;
  21023. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21024. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21025. }
  21026. }
  21027. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21028. };
  21029. RenderingGroup.prototype._renderSprites = function () {
  21030. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21031. return;
  21032. }
  21033. // Sprites
  21034. var activeCamera = this._scene.activeCamera;
  21035. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21036. for (var id = 0; id < this._spriteManagers.length; id++) {
  21037. var spriteManager = this._spriteManagers.data[id];
  21038. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21039. spriteManager.render();
  21040. }
  21041. }
  21042. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21043. };
  21044. return RenderingGroup;
  21045. }());
  21046. BABYLON.RenderingGroup = RenderingGroup;
  21047. })(BABYLON || (BABYLON = {}));
  21048. //# sourceMappingURL=babylon.renderingGroup.js.map
  21049. var BABYLON;
  21050. (function (BABYLON) {
  21051. var ClickInfo = /** @class */ (function () {
  21052. function ClickInfo() {
  21053. this._singleClick = false;
  21054. this._doubleClick = false;
  21055. this._hasSwiped = false;
  21056. this._ignore = false;
  21057. }
  21058. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21059. get: function () {
  21060. return this._singleClick;
  21061. },
  21062. set: function (b) {
  21063. this._singleClick = b;
  21064. },
  21065. enumerable: true,
  21066. configurable: true
  21067. });
  21068. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21069. get: function () {
  21070. return this._doubleClick;
  21071. },
  21072. set: function (b) {
  21073. this._doubleClick = b;
  21074. },
  21075. enumerable: true,
  21076. configurable: true
  21077. });
  21078. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21079. get: function () {
  21080. return this._hasSwiped;
  21081. },
  21082. set: function (b) {
  21083. this._hasSwiped = b;
  21084. },
  21085. enumerable: true,
  21086. configurable: true
  21087. });
  21088. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21089. get: function () {
  21090. return this._ignore;
  21091. },
  21092. set: function (b) {
  21093. this._ignore = b;
  21094. },
  21095. enumerable: true,
  21096. configurable: true
  21097. });
  21098. return ClickInfo;
  21099. }());
  21100. /**
  21101. * This class is used by the onRenderingGroupObservable
  21102. */
  21103. var RenderingGroupInfo = /** @class */ (function () {
  21104. function RenderingGroupInfo() {
  21105. }
  21106. /**
  21107. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21108. * This stage will be fired no matter what
  21109. */
  21110. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21111. /**
  21112. * Called before opaque object are rendered.
  21113. * This stage will be fired only if there's 3D Opaque content to render
  21114. */
  21115. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21116. /**
  21117. * Called after the opaque objects are rendered and before the transparent ones
  21118. * This stage will be fired only if there's 3D transparent content to render
  21119. */
  21120. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21121. /**
  21122. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21123. * This stage will be fired no matter what
  21124. */
  21125. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21126. return RenderingGroupInfo;
  21127. }());
  21128. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21129. /**
  21130. * Represents a scene to be rendered by the engine.
  21131. * @see http://doc.babylonjs.com/page.php?p=21911
  21132. */
  21133. var Scene = /** @class */ (function () {
  21134. /**
  21135. * @constructor
  21136. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21137. */
  21138. function Scene(engine) {
  21139. // Members
  21140. this.autoClear = true;
  21141. this.autoClearDepthAndStencil = true;
  21142. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21143. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21144. this.forceWireframe = false;
  21145. this._forcePointsCloud = false;
  21146. this.forceShowBoundingBoxes = false;
  21147. this.animationsEnabled = true;
  21148. this.useConstantAnimationDeltaTime = false;
  21149. this.constantlyUpdateMeshUnderPointer = false;
  21150. this.hoverCursor = "pointer";
  21151. this.defaultCursor = "";
  21152. /**
  21153. * This is used to call preventDefault() on pointer down
  21154. * in order to block unwanted artifacts like system double clicks
  21155. */
  21156. this.preventDefaultOnPointerDown = true;
  21157. // Metadata
  21158. this.metadata = null;
  21159. /**
  21160. * An event triggered when the scene is disposed.
  21161. * @type {BABYLON.Observable}
  21162. */
  21163. this.onDisposeObservable = new BABYLON.Observable();
  21164. /**
  21165. * An event triggered before rendering the scene (right after animations and physics)
  21166. * @type {BABYLON.Observable}
  21167. */
  21168. this.onBeforeRenderObservable = new BABYLON.Observable();
  21169. /**
  21170. * An event triggered after rendering the scene
  21171. * @type {BABYLON.Observable}
  21172. */
  21173. this.onAfterRenderObservable = new BABYLON.Observable();
  21174. /**
  21175. * An event triggered before animating the scene
  21176. * @type {BABYLON.Observable}
  21177. */
  21178. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21179. /**
  21180. * An event triggered after animations processing
  21181. * @type {BABYLON.Observable}
  21182. */
  21183. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21184. /**
  21185. * An event triggered before draw calls are ready to be sent
  21186. * @type {BABYLON.Observable}
  21187. */
  21188. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21189. /**
  21190. * An event triggered after draw calls have been sent
  21191. * @type {BABYLON.Observable}
  21192. */
  21193. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21194. /**
  21195. * An event triggered when physic simulation is about to be run
  21196. * @type {BABYLON.Observable}
  21197. */
  21198. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21199. /**
  21200. * An event triggered when physic simulation has been done
  21201. * @type {BABYLON.Observable}
  21202. */
  21203. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21204. /**
  21205. * An event triggered when the scene is ready
  21206. * @type {BABYLON.Observable}
  21207. */
  21208. this.onReadyObservable = new BABYLON.Observable();
  21209. /**
  21210. * An event triggered before rendering a camera
  21211. * @type {BABYLON.Observable}
  21212. */
  21213. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21214. /**
  21215. * An event triggered after rendering a camera
  21216. * @type {BABYLON.Observable}
  21217. */
  21218. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21219. /**
  21220. * An event triggered when active meshes evaluation is about to start
  21221. * @type {BABYLON.Observable}
  21222. */
  21223. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21224. /**
  21225. * An event triggered when active meshes evaluation is done
  21226. * @type {BABYLON.Observable}
  21227. */
  21228. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21229. /**
  21230. * An event triggered when particles rendering is about to start
  21231. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21232. * @type {BABYLON.Observable}
  21233. */
  21234. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21235. /**
  21236. * An event triggered when particles rendering is done
  21237. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21238. * @type {BABYLON.Observable}
  21239. */
  21240. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21241. /**
  21242. * An event triggered when sprites rendering is about to start
  21243. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21244. * @type {BABYLON.Observable}
  21245. */
  21246. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21247. /**
  21248. * An event triggered when sprites rendering is done
  21249. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21250. * @type {BABYLON.Observable}
  21251. */
  21252. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21253. /**
  21254. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21255. * @type {BABYLON.Observable}
  21256. */
  21257. this.onDataLoadedObservable = new BABYLON.Observable();
  21258. /**
  21259. * An event triggered when a camera is created
  21260. * @type {BABYLON.Observable}
  21261. */
  21262. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21263. /**
  21264. * An event triggered when a camera is removed
  21265. * @type {BABYLON.Observable}
  21266. */
  21267. this.onCameraRemovedObservable = new BABYLON.Observable();
  21268. /**
  21269. * An event triggered when a light is created
  21270. * @type {BABYLON.Observable}
  21271. */
  21272. this.onNewLightAddedObservable = new BABYLON.Observable();
  21273. /**
  21274. * An event triggered when a light is removed
  21275. * @type {BABYLON.Observable}
  21276. */
  21277. this.onLightRemovedObservable = new BABYLON.Observable();
  21278. /**
  21279. * An event triggered when a geometry is created
  21280. * @type {BABYLON.Observable}
  21281. */
  21282. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21283. /**
  21284. * An event triggered when a geometry is removed
  21285. * @type {BABYLON.Observable}
  21286. */
  21287. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21288. /**
  21289. * An event triggered when a transform node is created
  21290. * @type {BABYLON.Observable}
  21291. */
  21292. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21293. /**
  21294. * An event triggered when a transform node is removed
  21295. * @type {BABYLON.Observable}
  21296. */
  21297. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21298. /**
  21299. * An event triggered when a mesh is created
  21300. * @type {BABYLON.Observable}
  21301. */
  21302. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21303. /**
  21304. * An event triggered when a mesh is removed
  21305. * @type {BABYLON.Observable}
  21306. */
  21307. this.onMeshRemovedObservable = new BABYLON.Observable();
  21308. /**
  21309. * An event triggered when render targets are about to be rendered
  21310. * Can happen multiple times per frame.
  21311. * @type {BABYLON.Observable}
  21312. */
  21313. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21314. /**
  21315. * An event triggered when render targets were rendered.
  21316. * Can happen multiple times per frame.
  21317. * @type {BABYLON.Observable}
  21318. */
  21319. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21320. /**
  21321. * An event triggered before calculating deterministic simulation step
  21322. * @type {BABYLON.Observable}
  21323. */
  21324. this.onBeforeStepObservable = new BABYLON.Observable();
  21325. /**
  21326. * An event triggered after calculating deterministic simulation step
  21327. * @type {BABYLON.Observable}
  21328. */
  21329. this.onAfterStepObservable = new BABYLON.Observable();
  21330. /**
  21331. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21332. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21333. * 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)
  21334. */
  21335. this.onRenderingGroupObservable = new BABYLON.Observable();
  21336. // Animations
  21337. this.animations = [];
  21338. /**
  21339. * 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).
  21340. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21341. */
  21342. this.onPrePointerObservable = new BABYLON.Observable();
  21343. /**
  21344. * Observable event triggered each time an input event is received from the rendering canvas
  21345. */
  21346. this.onPointerObservable = new BABYLON.Observable();
  21347. this._meshPickProceed = false;
  21348. this._currentPickResult = null;
  21349. this._previousPickResult = null;
  21350. this._totalPointersPressed = 0;
  21351. this._doubleClickOccured = false;
  21352. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21353. this.cameraToUseForPointers = null;
  21354. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21355. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21356. this._startingPointerTime = 0;
  21357. this._previousStartingPointerTime = 0;
  21358. // Deterministic lockstep
  21359. this._timeAccumulator = 0;
  21360. this._currentStepId = 0;
  21361. this._currentInternalStep = 0;
  21362. // Keyboard
  21363. /**
  21364. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21365. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21366. */
  21367. this.onPreKeyboardObservable = new BABYLON.Observable();
  21368. /**
  21369. * Observable event triggered each time an keyboard event is received from the hosting window
  21370. */
  21371. this.onKeyboardObservable = new BABYLON.Observable();
  21372. // Coordinate system
  21373. /**
  21374. * use right-handed coordinate system on this scene.
  21375. * @type {boolean}
  21376. */
  21377. this._useRightHandedSystem = false;
  21378. // Fog
  21379. this._fogEnabled = true;
  21380. this._fogMode = Scene.FOGMODE_NONE;
  21381. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21382. this.fogDensity = 0.1;
  21383. this.fogStart = 0;
  21384. this.fogEnd = 1000.0;
  21385. // Lights
  21386. /**
  21387. * is shadow enabled on this scene.
  21388. * @type {boolean}
  21389. */
  21390. this._shadowsEnabled = true;
  21391. /**
  21392. * is light enabled on this scene.
  21393. * @type {boolean}
  21394. */
  21395. this._lightsEnabled = true;
  21396. /**
  21397. * All of the lights added to this scene.
  21398. * @see BABYLON.Light
  21399. * @type {BABYLON.Light[]}
  21400. */
  21401. this.lights = new Array();
  21402. // Cameras
  21403. /** All of the cameras added to this scene. */
  21404. this.cameras = new Array();
  21405. /** All of the active cameras added to this scene. */
  21406. this.activeCameras = new Array();
  21407. // Meshes
  21408. /**
  21409. * All of the tranform nodes added to this scene.
  21410. * @see BABYLON.TransformNode
  21411. * @type {BABYLON.TransformNode[]}
  21412. */
  21413. this.transformNodes = new Array();
  21414. /**
  21415. * All of the (abstract) meshes added to this scene.
  21416. * @see BABYLON.AbstractMesh
  21417. * @type {BABYLON.AbstractMesh[]}
  21418. */
  21419. this.meshes = new Array();
  21420. /**
  21421. * All of the animation groups added to this scene.
  21422. * @see BABYLON.AnimationGroup
  21423. * @type {BABYLON.AnimationGroup[]}
  21424. */
  21425. this.animationGroups = new Array();
  21426. // Geometries
  21427. this._geometries = new Array();
  21428. this.materials = new Array();
  21429. this.multiMaterials = new Array();
  21430. // Textures
  21431. this._texturesEnabled = true;
  21432. this.textures = new Array();
  21433. // Particles
  21434. this.particlesEnabled = true;
  21435. this.particleSystems = new Array();
  21436. // Sprites
  21437. this.spritesEnabled = true;
  21438. this.spriteManagers = new Array();
  21439. /**
  21440. * The list of layers (background and foreground) of the scene.
  21441. */
  21442. this.layers = new Array();
  21443. /**
  21444. * The list of effect layers (highlights/glow) contained in the scene.
  21445. */
  21446. this.effectLayers = new Array();
  21447. // Skeletons
  21448. this._skeletonsEnabled = true;
  21449. this.skeletons = new Array();
  21450. // Morph targets
  21451. this.morphTargetManagers = new Array();
  21452. // Lens flares
  21453. this.lensFlaresEnabled = true;
  21454. this.lensFlareSystems = new Array();
  21455. // Collisions
  21456. this.collisionsEnabled = true;
  21457. /** Defines the gravity applied to this scene */
  21458. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21459. // Postprocesses
  21460. this.postProcesses = new Array();
  21461. this.postProcessesEnabled = true;
  21462. // Customs render targets
  21463. this.renderTargetsEnabled = true;
  21464. this.dumpNextRenderTargets = false;
  21465. this.customRenderTargets = new Array();
  21466. // Imported meshes
  21467. this.importedMeshesFiles = new Array();
  21468. // Probes
  21469. this.probesEnabled = true;
  21470. this.reflectionProbes = new Array();
  21471. this._actionManagers = new Array();
  21472. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21473. // Procedural textures
  21474. this.proceduralTexturesEnabled = true;
  21475. this._proceduralTextures = new Array();
  21476. this.soundTracks = new Array();
  21477. this._audioEnabled = true;
  21478. this._headphone = false;
  21479. // Performance counters
  21480. this._totalVertices = new BABYLON.PerfCounter();
  21481. this._activeIndices = new BABYLON.PerfCounter();
  21482. this._activeParticles = new BABYLON.PerfCounter();
  21483. this._activeBones = new BABYLON.PerfCounter();
  21484. this._animationTime = 0;
  21485. this.animationTimeScale = 1;
  21486. this._renderId = 0;
  21487. this._executeWhenReadyTimeoutId = -1;
  21488. this._intermediateRendering = false;
  21489. this._viewUpdateFlag = -1;
  21490. this._projectionUpdateFlag = -1;
  21491. this._alternateViewUpdateFlag = -1;
  21492. this._alternateProjectionUpdateFlag = -1;
  21493. this._toBeDisposed = new BABYLON.SmartArray(256);
  21494. this._activeRequests = new Array();
  21495. this._pendingData = new Array();
  21496. this._isDisposed = false;
  21497. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21498. this._activeMeshes = new BABYLON.SmartArray(256);
  21499. this._processedMaterials = new BABYLON.SmartArray(256);
  21500. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21501. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21502. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21503. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21504. this._activeAnimatables = new Array();
  21505. this._transformMatrix = BABYLON.Matrix.Zero();
  21506. this._useAlternateCameraConfiguration = false;
  21507. this._alternateRendering = false;
  21508. this.requireLightSorting = false;
  21509. this._depthRenderer = {};
  21510. this._activeMeshesFrozen = false;
  21511. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21512. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21513. this._engine.scenes.push(this);
  21514. this._uid = null;
  21515. this._renderingManager = new BABYLON.RenderingManager(this);
  21516. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21517. if (BABYLON.OutlineRenderer) {
  21518. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21519. }
  21520. if (BABYLON.Tools.IsWindowObjectExist()) {
  21521. this.attachControl();
  21522. }
  21523. //simplification queue
  21524. if (BABYLON.SimplificationQueue) {
  21525. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21526. }
  21527. //collision coordinator initialization. For now legacy per default.
  21528. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21529. // Uniform Buffer
  21530. this._createUbo();
  21531. // Default Image processing definition.
  21532. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21533. }
  21534. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21535. /** The fog is deactivated */
  21536. get: function () {
  21537. return Scene._FOGMODE_NONE;
  21538. },
  21539. enumerable: true,
  21540. configurable: true
  21541. });
  21542. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21543. /** The fog density is following an exponential function */
  21544. get: function () {
  21545. return Scene._FOGMODE_EXP;
  21546. },
  21547. enumerable: true,
  21548. configurable: true
  21549. });
  21550. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21551. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21552. get: function () {
  21553. return Scene._FOGMODE_EXP2;
  21554. },
  21555. enumerable: true,
  21556. configurable: true
  21557. });
  21558. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21559. /** The fog density is following a linear function. */
  21560. get: function () {
  21561. return Scene._FOGMODE_LINEAR;
  21562. },
  21563. enumerable: true,
  21564. configurable: true
  21565. });
  21566. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21567. /**
  21568. * Texture used in all pbr material as the reflection texture.
  21569. * As in the majority of the scene they are the same (exception for multi room and so on),
  21570. * this is easier to reference from here than from all the materials.
  21571. */
  21572. get: function () {
  21573. return this._environmentTexture;
  21574. },
  21575. /**
  21576. * Texture used in all pbr material as the reflection texture.
  21577. * As in the majority of the scene they are the same (exception for multi room and so on),
  21578. * this is easier to set here than in all the materials.
  21579. */
  21580. set: function (value) {
  21581. if (this._environmentTexture === value) {
  21582. return;
  21583. }
  21584. this._environmentTexture = value;
  21585. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21586. },
  21587. enumerable: true,
  21588. configurable: true
  21589. });
  21590. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21591. /**
  21592. * Default image processing configuration used either in the rendering
  21593. * Forward main pass or through the imageProcessingPostProcess if present.
  21594. * As in the majority of the scene they are the same (exception for multi camera),
  21595. * this is easier to reference from here than from all the materials and post process.
  21596. *
  21597. * No setter as we it is a shared configuration, you can set the values instead.
  21598. */
  21599. get: function () {
  21600. return this._imageProcessingConfiguration;
  21601. },
  21602. enumerable: true,
  21603. configurable: true
  21604. });
  21605. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21606. get: function () {
  21607. return this._forcePointsCloud;
  21608. },
  21609. set: function (value) {
  21610. if (this._forcePointsCloud === value) {
  21611. return;
  21612. }
  21613. this._forcePointsCloud = value;
  21614. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21615. },
  21616. enumerable: true,
  21617. configurable: true
  21618. });
  21619. Object.defineProperty(Scene.prototype, "onDispose", {
  21620. /** A function to be executed when this scene is disposed. */
  21621. set: function (callback) {
  21622. if (this._onDisposeObserver) {
  21623. this.onDisposeObservable.remove(this._onDisposeObserver);
  21624. }
  21625. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21626. },
  21627. enumerable: true,
  21628. configurable: true
  21629. });
  21630. Object.defineProperty(Scene.prototype, "beforeRender", {
  21631. /** A function to be executed before rendering this scene */
  21632. set: function (callback) {
  21633. if (this._onBeforeRenderObserver) {
  21634. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21635. }
  21636. if (callback) {
  21637. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21638. }
  21639. },
  21640. enumerable: true,
  21641. configurable: true
  21642. });
  21643. Object.defineProperty(Scene.prototype, "afterRender", {
  21644. /** A function to be executed after rendering this scene */
  21645. set: function (callback) {
  21646. if (this._onAfterRenderObserver) {
  21647. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21648. }
  21649. if (callback) {
  21650. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21651. }
  21652. },
  21653. enumerable: true,
  21654. configurable: true
  21655. });
  21656. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  21657. set: function (callback) {
  21658. if (this._onBeforeCameraRenderObserver) {
  21659. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  21660. }
  21661. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  21662. },
  21663. enumerable: true,
  21664. configurable: true
  21665. });
  21666. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  21667. set: function (callback) {
  21668. if (this._onAfterCameraRenderObserver) {
  21669. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  21670. }
  21671. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  21672. },
  21673. enumerable: true,
  21674. configurable: true
  21675. });
  21676. Object.defineProperty(Scene.prototype, "gamepadManager", {
  21677. get: function () {
  21678. if (!this._gamepadManager) {
  21679. this._gamepadManager = new BABYLON.GamepadManager(this);
  21680. }
  21681. return this._gamepadManager;
  21682. },
  21683. enumerable: true,
  21684. configurable: true
  21685. });
  21686. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  21687. get: function () {
  21688. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  21689. },
  21690. enumerable: true,
  21691. configurable: true
  21692. });
  21693. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  21694. get: function () {
  21695. return this._useRightHandedSystem;
  21696. },
  21697. set: function (value) {
  21698. if (this._useRightHandedSystem === value) {
  21699. return;
  21700. }
  21701. this._useRightHandedSystem = value;
  21702. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21703. },
  21704. enumerable: true,
  21705. configurable: true
  21706. });
  21707. Scene.prototype.setStepId = function (newStepId) {
  21708. this._currentStepId = newStepId;
  21709. };
  21710. ;
  21711. Scene.prototype.getStepId = function () {
  21712. return this._currentStepId;
  21713. };
  21714. ;
  21715. Scene.prototype.getInternalStep = function () {
  21716. return this._currentInternalStep;
  21717. };
  21718. ;
  21719. Object.defineProperty(Scene.prototype, "fogEnabled", {
  21720. get: function () {
  21721. return this._fogEnabled;
  21722. },
  21723. /**
  21724. * is fog enabled on this scene.
  21725. */
  21726. set: function (value) {
  21727. if (this._fogEnabled === value) {
  21728. return;
  21729. }
  21730. this._fogEnabled = value;
  21731. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21732. },
  21733. enumerable: true,
  21734. configurable: true
  21735. });
  21736. Object.defineProperty(Scene.prototype, "fogMode", {
  21737. get: function () {
  21738. return this._fogMode;
  21739. },
  21740. set: function (value) {
  21741. if (this._fogMode === value) {
  21742. return;
  21743. }
  21744. this._fogMode = value;
  21745. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21746. },
  21747. enumerable: true,
  21748. configurable: true
  21749. });
  21750. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  21751. get: function () {
  21752. return this._shadowsEnabled;
  21753. },
  21754. set: function (value) {
  21755. if (this._shadowsEnabled === value) {
  21756. return;
  21757. }
  21758. this._shadowsEnabled = value;
  21759. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21760. },
  21761. enumerable: true,
  21762. configurable: true
  21763. });
  21764. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  21765. get: function () {
  21766. return this._lightsEnabled;
  21767. },
  21768. set: function (value) {
  21769. if (this._lightsEnabled === value) {
  21770. return;
  21771. }
  21772. this._lightsEnabled = value;
  21773. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21774. },
  21775. enumerable: true,
  21776. configurable: true
  21777. });
  21778. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  21779. /** The default material used on meshes when no material is affected */
  21780. get: function () {
  21781. if (!this._defaultMaterial) {
  21782. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  21783. }
  21784. return this._defaultMaterial;
  21785. },
  21786. /** The default material used on meshes when no material is affected */
  21787. set: function (value) {
  21788. this._defaultMaterial = value;
  21789. },
  21790. enumerable: true,
  21791. configurable: true
  21792. });
  21793. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  21794. get: function () {
  21795. return this._texturesEnabled;
  21796. },
  21797. set: function (value) {
  21798. if (this._texturesEnabled === value) {
  21799. return;
  21800. }
  21801. this._texturesEnabled = value;
  21802. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21803. },
  21804. enumerable: true,
  21805. configurable: true
  21806. });
  21807. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  21808. get: function () {
  21809. return this._skeletonsEnabled;
  21810. },
  21811. set: function (value) {
  21812. if (this._skeletonsEnabled === value) {
  21813. return;
  21814. }
  21815. this._skeletonsEnabled = value;
  21816. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  21817. },
  21818. enumerable: true,
  21819. configurable: true
  21820. });
  21821. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  21822. get: function () {
  21823. if (!this._postProcessRenderPipelineManager) {
  21824. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  21825. }
  21826. return this._postProcessRenderPipelineManager;
  21827. },
  21828. enumerable: true,
  21829. configurable: true
  21830. });
  21831. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  21832. get: function () {
  21833. if (!this._mainSoundTrack) {
  21834. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  21835. }
  21836. return this._mainSoundTrack;
  21837. },
  21838. enumerable: true,
  21839. configurable: true
  21840. });
  21841. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  21842. get: function () {
  21843. return this._alternateRendering;
  21844. },
  21845. enumerable: true,
  21846. configurable: true
  21847. });
  21848. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  21849. get: function () {
  21850. return this._frustumPlanes;
  21851. },
  21852. enumerable: true,
  21853. configurable: true
  21854. });
  21855. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  21856. /**
  21857. * Gets the current geometry buffer associated to the scene.
  21858. */
  21859. get: function () {
  21860. return this._geometryBufferRenderer;
  21861. },
  21862. /**
  21863. * Sets the current geometry buffer for the scene.
  21864. */
  21865. set: function (geometryBufferRenderer) {
  21866. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  21867. this._geometryBufferRenderer = geometryBufferRenderer;
  21868. }
  21869. },
  21870. enumerable: true,
  21871. configurable: true
  21872. });
  21873. Object.defineProperty(Scene.prototype, "debugLayer", {
  21874. // Properties
  21875. get: function () {
  21876. if (!this._debugLayer) {
  21877. this._debugLayer = new BABYLON.DebugLayer(this);
  21878. }
  21879. return this._debugLayer;
  21880. },
  21881. enumerable: true,
  21882. configurable: true
  21883. });
  21884. Object.defineProperty(Scene.prototype, "workerCollisions", {
  21885. get: function () {
  21886. return this._workerCollisions;
  21887. },
  21888. set: function (enabled) {
  21889. if (!BABYLON.CollisionCoordinatorLegacy) {
  21890. return;
  21891. }
  21892. enabled = (enabled && !!Worker);
  21893. this._workerCollisions = enabled;
  21894. if (this.collisionCoordinator) {
  21895. this.collisionCoordinator.destroy();
  21896. }
  21897. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  21898. this.collisionCoordinator.init(this);
  21899. },
  21900. enumerable: true,
  21901. configurable: true
  21902. });
  21903. Object.defineProperty(Scene.prototype, "selectionOctree", {
  21904. get: function () {
  21905. return this._selectionOctree;
  21906. },
  21907. enumerable: true,
  21908. configurable: true
  21909. });
  21910. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  21911. /**
  21912. * The mesh that is currently under the pointer.
  21913. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  21914. */
  21915. get: function () {
  21916. return this._pointerOverMesh;
  21917. },
  21918. enumerable: true,
  21919. configurable: true
  21920. });
  21921. Object.defineProperty(Scene.prototype, "pointerX", {
  21922. /**
  21923. * Current on-screen X position of the pointer
  21924. * @return {number} X position of the pointer
  21925. */
  21926. get: function () {
  21927. return this._pointerX;
  21928. },
  21929. enumerable: true,
  21930. configurable: true
  21931. });
  21932. Object.defineProperty(Scene.prototype, "pointerY", {
  21933. /**
  21934. * Current on-screen Y position of the pointer
  21935. * @return {number} Y position of the pointer
  21936. */
  21937. get: function () {
  21938. return this._pointerY;
  21939. },
  21940. enumerable: true,
  21941. configurable: true
  21942. });
  21943. Scene.prototype.getCachedMaterial = function () {
  21944. return this._cachedMaterial;
  21945. };
  21946. Scene.prototype.getCachedEffect = function () {
  21947. return this._cachedEffect;
  21948. };
  21949. Scene.prototype.getCachedVisibility = function () {
  21950. return this._cachedVisibility;
  21951. };
  21952. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  21953. if (visibility === void 0) { visibility = 1; }
  21954. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  21955. };
  21956. Scene.prototype.getBoundingBoxRenderer = function () {
  21957. if (!this._boundingBoxRenderer) {
  21958. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  21959. }
  21960. return this._boundingBoxRenderer;
  21961. };
  21962. Scene.prototype.getOutlineRenderer = function () {
  21963. return this._outlineRenderer;
  21964. };
  21965. Scene.prototype.getEngine = function () {
  21966. return this._engine;
  21967. };
  21968. Scene.prototype.getTotalVertices = function () {
  21969. return this._totalVertices.current;
  21970. };
  21971. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  21972. get: function () {
  21973. return this._totalVertices;
  21974. },
  21975. enumerable: true,
  21976. configurable: true
  21977. });
  21978. Scene.prototype.getActiveIndices = function () {
  21979. return this._activeIndices.current;
  21980. };
  21981. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  21982. get: function () {
  21983. return this._activeIndices;
  21984. },
  21985. enumerable: true,
  21986. configurable: true
  21987. });
  21988. Scene.prototype.getActiveParticles = function () {
  21989. return this._activeParticles.current;
  21990. };
  21991. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  21992. get: function () {
  21993. return this._activeParticles;
  21994. },
  21995. enumerable: true,
  21996. configurable: true
  21997. });
  21998. Scene.prototype.getActiveBones = function () {
  21999. return this._activeBones.current;
  22000. };
  22001. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22002. get: function () {
  22003. return this._activeBones;
  22004. },
  22005. enumerable: true,
  22006. configurable: true
  22007. });
  22008. // Stats
  22009. Scene.prototype.getInterFramePerfCounter = function () {
  22010. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22011. return 0;
  22012. };
  22013. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22014. get: function () {
  22015. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22016. return null;
  22017. },
  22018. enumerable: true,
  22019. configurable: true
  22020. });
  22021. Scene.prototype.getLastFrameDuration = function () {
  22022. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22023. return 0;
  22024. };
  22025. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22026. get: function () {
  22027. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22028. return null;
  22029. },
  22030. enumerable: true,
  22031. configurable: true
  22032. });
  22033. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22034. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22035. return 0;
  22036. };
  22037. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22038. get: function () {
  22039. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22040. return null;
  22041. },
  22042. enumerable: true,
  22043. configurable: true
  22044. });
  22045. Scene.prototype.getActiveMeshes = function () {
  22046. return this._activeMeshes;
  22047. };
  22048. Scene.prototype.getRenderTargetsDuration = function () {
  22049. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22050. return 0;
  22051. };
  22052. Scene.prototype.getRenderDuration = function () {
  22053. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22054. return 0;
  22055. };
  22056. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22057. get: function () {
  22058. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22059. return null;
  22060. },
  22061. enumerable: true,
  22062. configurable: true
  22063. });
  22064. Scene.prototype.getParticlesDuration = function () {
  22065. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22066. return 0;
  22067. };
  22068. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22069. get: function () {
  22070. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22071. return null;
  22072. },
  22073. enumerable: true,
  22074. configurable: true
  22075. });
  22076. Scene.prototype.getSpritesDuration = function () {
  22077. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22078. return 0;
  22079. };
  22080. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22081. get: function () {
  22082. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22083. return null;
  22084. },
  22085. enumerable: true,
  22086. configurable: true
  22087. });
  22088. Scene.prototype.getAnimationRatio = function () {
  22089. return this._animationRatio;
  22090. };
  22091. Scene.prototype.getRenderId = function () {
  22092. return this._renderId;
  22093. };
  22094. Scene.prototype.incrementRenderId = function () {
  22095. this._renderId++;
  22096. };
  22097. Scene.prototype._updatePointerPosition = function (evt) {
  22098. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22099. if (!canvasRect) {
  22100. return;
  22101. }
  22102. this._pointerX = evt.clientX - canvasRect.left;
  22103. this._pointerY = evt.clientY - canvasRect.top;
  22104. this._unTranslatedPointerX = this._pointerX;
  22105. this._unTranslatedPointerY = this._pointerY;
  22106. };
  22107. Scene.prototype._createUbo = function () {
  22108. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22109. this._sceneUbo.addUniform("viewProjection", 16);
  22110. this._sceneUbo.addUniform("view", 16);
  22111. };
  22112. Scene.prototype._createAlternateUbo = function () {
  22113. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22114. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22115. this._alternateSceneUbo.addUniform("view", 16);
  22116. };
  22117. // Pointers handling
  22118. /**
  22119. * Use this method to simulate a pointer move on a mesh
  22120. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22121. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22122. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22123. */
  22124. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22125. var evt = new PointerEvent("pointermove", pointerEventInit);
  22126. return this._processPointerMove(pickResult, evt);
  22127. };
  22128. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22129. var canvas = this._engine.getRenderingCanvas();
  22130. if (!canvas) {
  22131. return this;
  22132. }
  22133. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22134. this.setPointerOverSprite(null);
  22135. this.setPointerOverMesh(pickResult.pickedMesh);
  22136. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22137. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22138. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22139. }
  22140. else {
  22141. canvas.style.cursor = this.hoverCursor;
  22142. }
  22143. }
  22144. else {
  22145. canvas.style.cursor = this.defaultCursor;
  22146. }
  22147. }
  22148. else {
  22149. this.setPointerOverMesh(null);
  22150. // Sprites
  22151. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22152. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22153. this.setPointerOverSprite(pickResult.pickedSprite);
  22154. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22155. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22156. }
  22157. else {
  22158. canvas.style.cursor = this.hoverCursor;
  22159. }
  22160. }
  22161. else {
  22162. this.setPointerOverSprite(null);
  22163. // Restore pointer
  22164. canvas.style.cursor = this.defaultCursor;
  22165. }
  22166. }
  22167. if (pickResult) {
  22168. if (this.onPointerMove) {
  22169. this.onPointerMove(evt, pickResult);
  22170. }
  22171. if (this.onPointerObservable.hasObservers()) {
  22172. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22173. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22174. this.onPointerObservable.notifyObservers(pi, type);
  22175. }
  22176. }
  22177. return this;
  22178. };
  22179. /**
  22180. * Use this method to simulate a pointer down on a mesh
  22181. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22182. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22183. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22184. */
  22185. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22186. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22187. return this._processPointerDown(pickResult, evt);
  22188. };
  22189. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22190. var _this = this;
  22191. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22192. this._pickedDownMesh = pickResult.pickedMesh;
  22193. var actionManager = pickResult.pickedMesh.actionManager;
  22194. if (actionManager) {
  22195. if (actionManager.hasPickTriggers) {
  22196. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22197. switch (evt.button) {
  22198. case 0:
  22199. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22200. break;
  22201. case 1:
  22202. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22203. break;
  22204. case 2:
  22205. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22206. break;
  22207. }
  22208. }
  22209. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22210. window.setTimeout(function () {
  22211. 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);
  22212. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22213. if (_this._totalPointersPressed !== 0 &&
  22214. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22215. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22216. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22217. _this._startingPointerTime = 0;
  22218. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22219. }
  22220. }
  22221. }, Scene.LongPressDelay);
  22222. }
  22223. }
  22224. }
  22225. if (pickResult) {
  22226. if (this.onPointerDown) {
  22227. this.onPointerDown(evt, pickResult);
  22228. }
  22229. if (this.onPointerObservable.hasObservers()) {
  22230. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22231. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22232. this.onPointerObservable.notifyObservers(pi, type);
  22233. }
  22234. }
  22235. return this;
  22236. };
  22237. /**
  22238. * Use this method to simulate a pointer up on a mesh
  22239. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22240. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22241. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22242. */
  22243. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22244. var evt = new PointerEvent("pointerup", pointerEventInit);
  22245. var clickInfo = new ClickInfo();
  22246. clickInfo.singleClick = true;
  22247. clickInfo.ignore = true;
  22248. return this._processPointerUp(pickResult, evt, clickInfo);
  22249. };
  22250. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22251. if (pickResult && pickResult && pickResult.pickedMesh) {
  22252. this._pickedUpMesh = pickResult.pickedMesh;
  22253. if (this._pickedDownMesh === this._pickedUpMesh) {
  22254. if (this.onPointerPick) {
  22255. this.onPointerPick(evt, pickResult);
  22256. }
  22257. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22258. var type = BABYLON.PointerEventTypes.POINTERPICK;
  22259. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22260. this.onPointerObservable.notifyObservers(pi, type);
  22261. }
  22262. }
  22263. if (pickResult.pickedMesh.actionManager) {
  22264. if (clickInfo.ignore) {
  22265. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22266. }
  22267. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22268. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22269. }
  22270. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22271. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22272. }
  22273. }
  22274. }
  22275. if (this._pickedDownMesh &&
  22276. this._pickedDownMesh.actionManager &&
  22277. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22278. this._pickedDownMesh !== this._pickedUpMesh) {
  22279. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22280. }
  22281. if (this.onPointerUp) {
  22282. this.onPointerUp(evt, pickResult);
  22283. }
  22284. if (this.onPointerObservable.hasObservers()) {
  22285. if (!clickInfo.ignore) {
  22286. if (!clickInfo.hasSwiped) {
  22287. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22288. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22289. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22290. this.onPointerObservable.notifyObservers(pi, type);
  22291. }
  22292. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22293. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22294. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22295. this.onPointerObservable.notifyObservers(pi, type);
  22296. }
  22297. }
  22298. }
  22299. else {
  22300. var type = BABYLON.PointerEventTypes.POINTERUP;
  22301. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22302. this.onPointerObservable.notifyObservers(pi, type);
  22303. }
  22304. }
  22305. return this;
  22306. };
  22307. /**
  22308. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22309. * @param attachUp defines if you want to attach events to pointerup
  22310. * @param attachDown defines if you want to attach events to pointerdown
  22311. * @param attachMove defines if you want to attach events to pointermove
  22312. */
  22313. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22314. var _this = this;
  22315. if (attachUp === void 0) { attachUp = true; }
  22316. if (attachDown === void 0) { attachDown = true; }
  22317. if (attachMove === void 0) { attachMove = true; }
  22318. this._initActionManager = function (act, clickInfo) {
  22319. if (!_this._meshPickProceed) {
  22320. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22321. _this._currentPickResult = pickResult;
  22322. if (pickResult) {
  22323. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22324. }
  22325. _this._meshPickProceed = true;
  22326. }
  22327. return act;
  22328. };
  22329. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22330. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22331. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22332. btn !== _this._previousButtonPressed) {
  22333. _this._doubleClickOccured = false;
  22334. clickInfo.singleClick = true;
  22335. clickInfo.ignore = false;
  22336. cb(clickInfo, _this._currentPickResult);
  22337. }
  22338. };
  22339. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22340. var clickInfo = new ClickInfo();
  22341. _this._currentPickResult = null;
  22342. var act = null;
  22343. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22344. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22345. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22346. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22347. act = _this._initActionManager(act, clickInfo);
  22348. if (act)
  22349. checkPicking = act.hasPickTriggers;
  22350. }
  22351. if (checkPicking) {
  22352. var btn = evt.button;
  22353. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22354. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22355. if (!clickInfo.hasSwiped) {
  22356. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22357. if (!checkSingleClickImmediately) {
  22358. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22359. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22360. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22361. act = _this._initActionManager(act, clickInfo);
  22362. if (act)
  22363. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22364. }
  22365. }
  22366. if (checkSingleClickImmediately) {
  22367. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22368. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22369. btn !== _this._previousButtonPressed) {
  22370. clickInfo.singleClick = true;
  22371. cb(clickInfo, _this._currentPickResult);
  22372. }
  22373. }
  22374. else {
  22375. // wait that no double click has been raised during the double click delay
  22376. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22377. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22378. }
  22379. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22380. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22381. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22382. act = _this._initActionManager(act, clickInfo);
  22383. if (act)
  22384. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22385. }
  22386. if (checkDoubleClick) {
  22387. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22388. if (btn === _this._previousButtonPressed &&
  22389. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22390. !_this._doubleClickOccured) {
  22391. // pointer has not moved for 2 clicks, it's a double click
  22392. if (!clickInfo.hasSwiped &&
  22393. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22394. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22395. _this._previousStartingPointerTime = 0;
  22396. _this._doubleClickOccured = true;
  22397. clickInfo.doubleClick = true;
  22398. clickInfo.ignore = false;
  22399. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22400. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22401. }
  22402. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22403. cb(clickInfo, _this._currentPickResult);
  22404. }
  22405. else {
  22406. _this._doubleClickOccured = false;
  22407. _this._previousStartingPointerTime = _this._startingPointerTime;
  22408. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22409. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22410. _this._previousButtonPressed = btn;
  22411. if (Scene.ExclusiveDoubleClickMode) {
  22412. if (_this._previousDelayedSimpleClickTimeout) {
  22413. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22414. }
  22415. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22416. cb(clickInfo, _this._previousPickResult);
  22417. }
  22418. else {
  22419. cb(clickInfo, _this._currentPickResult);
  22420. }
  22421. }
  22422. }
  22423. else {
  22424. _this._doubleClickOccured = false;
  22425. _this._previousStartingPointerTime = _this._startingPointerTime;
  22426. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22427. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22428. _this._previousButtonPressed = btn;
  22429. }
  22430. }
  22431. }
  22432. }
  22433. clickInfo.ignore = true;
  22434. cb(clickInfo, _this._currentPickResult);
  22435. };
  22436. this._spritePredicate = function (sprite) {
  22437. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22438. };
  22439. this._onPointerMove = function (evt) {
  22440. _this._updatePointerPosition(evt);
  22441. // PreObservable support
  22442. if (_this.onPrePointerObservable.hasObservers()) {
  22443. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22444. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22445. _this.onPrePointerObservable.notifyObservers(pi, type);
  22446. if (pi.skipOnPointerObservable) {
  22447. return;
  22448. }
  22449. }
  22450. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22451. return;
  22452. }
  22453. if (!_this.pointerMovePredicate) {
  22454. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22455. }
  22456. // Meshes
  22457. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22458. _this._processPointerMove(pickResult, evt);
  22459. };
  22460. this._onPointerDown = function (evt) {
  22461. _this._totalPointersPressed++;
  22462. _this._pickedDownMesh = null;
  22463. _this._meshPickProceed = false;
  22464. _this._updatePointerPosition(evt);
  22465. if (_this.preventDefaultOnPointerDown && canvas) {
  22466. evt.preventDefault();
  22467. canvas.focus();
  22468. }
  22469. // PreObservable support
  22470. if (_this.onPrePointerObservable.hasObservers()) {
  22471. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22472. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22473. _this.onPrePointerObservable.notifyObservers(pi, type);
  22474. if (pi.skipOnPointerObservable) {
  22475. return;
  22476. }
  22477. }
  22478. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22479. return;
  22480. }
  22481. _this._startingPointerPosition.x = _this._pointerX;
  22482. _this._startingPointerPosition.y = _this._pointerY;
  22483. _this._startingPointerTime = new Date().getTime();
  22484. if (!_this.pointerDownPredicate) {
  22485. _this.pointerDownPredicate = function (mesh) {
  22486. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22487. };
  22488. }
  22489. // Meshes
  22490. _this._pickedDownMesh = null;
  22491. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22492. _this._processPointerDown(pickResult, evt);
  22493. // Sprites
  22494. _this._pickedDownSprite = null;
  22495. if (_this.spriteManagers.length > 0) {
  22496. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22497. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22498. if (pickResult.pickedSprite.actionManager) {
  22499. _this._pickedDownSprite = pickResult.pickedSprite;
  22500. switch (evt.button) {
  22501. case 0:
  22502. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22503. break;
  22504. case 1:
  22505. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22506. break;
  22507. case 2:
  22508. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22509. break;
  22510. }
  22511. if (pickResult.pickedSprite.actionManager) {
  22512. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22513. }
  22514. }
  22515. }
  22516. }
  22517. };
  22518. this._onPointerUp = function (evt) {
  22519. if (_this._totalPointersPressed === 0) {
  22520. return; // So we need to test it the pointer down was pressed before.
  22521. }
  22522. _this._totalPointersPressed--;
  22523. _this._pickedUpMesh = null;
  22524. _this._meshPickProceed = false;
  22525. _this._updatePointerPosition(evt);
  22526. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22527. // PreObservable support
  22528. if (_this.onPrePointerObservable.hasObservers()) {
  22529. if (!clickInfo.ignore) {
  22530. if (!clickInfo.hasSwiped) {
  22531. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22532. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22533. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22534. _this.onPrePointerObservable.notifyObservers(pi, type);
  22535. if (pi.skipOnPointerObservable) {
  22536. return;
  22537. }
  22538. }
  22539. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22540. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22541. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22542. _this.onPrePointerObservable.notifyObservers(pi, type);
  22543. if (pi.skipOnPointerObservable) {
  22544. return;
  22545. }
  22546. }
  22547. }
  22548. }
  22549. else {
  22550. var type = BABYLON.PointerEventTypes.POINTERUP;
  22551. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22552. _this.onPrePointerObservable.notifyObservers(pi, type);
  22553. if (pi.skipOnPointerObservable) {
  22554. return;
  22555. }
  22556. }
  22557. }
  22558. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22559. return;
  22560. }
  22561. if (!_this.pointerUpPredicate) {
  22562. _this.pointerUpPredicate = function (mesh) {
  22563. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22564. };
  22565. }
  22566. // Meshes
  22567. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22568. _this._initActionManager(null, clickInfo);
  22569. }
  22570. if (!pickResult) {
  22571. pickResult = _this._currentPickResult;
  22572. }
  22573. _this._processPointerUp(pickResult, evt, clickInfo);
  22574. // Sprites
  22575. if (_this.spriteManagers.length > 0) {
  22576. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22577. if (spritePickResult) {
  22578. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22579. if (spritePickResult.pickedSprite.actionManager) {
  22580. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22581. if (spritePickResult.pickedSprite.actionManager) {
  22582. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22583. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22584. }
  22585. }
  22586. }
  22587. }
  22588. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22589. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22590. }
  22591. }
  22592. }
  22593. _this._previousPickResult = _this._currentPickResult;
  22594. });
  22595. };
  22596. this._onKeyDown = function (evt) {
  22597. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22598. if (_this.onPreKeyboardObservable.hasObservers()) {
  22599. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22600. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22601. if (pi.skipOnPointerObservable) {
  22602. return;
  22603. }
  22604. }
  22605. if (_this.onKeyboardObservable.hasObservers()) {
  22606. var pi = new BABYLON.KeyboardInfo(type, evt);
  22607. _this.onKeyboardObservable.notifyObservers(pi, type);
  22608. }
  22609. if (_this.actionManager) {
  22610. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22611. }
  22612. };
  22613. this._onKeyUp = function (evt) {
  22614. var type = BABYLON.KeyboardEventTypes.KEYUP;
  22615. if (_this.onPreKeyboardObservable.hasObservers()) {
  22616. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22617. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22618. if (pi.skipOnPointerObservable) {
  22619. return;
  22620. }
  22621. }
  22622. if (_this.onKeyboardObservable.hasObservers()) {
  22623. var pi = new BABYLON.KeyboardInfo(type, evt);
  22624. _this.onKeyboardObservable.notifyObservers(pi, type);
  22625. }
  22626. if (_this.actionManager) {
  22627. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22628. }
  22629. };
  22630. var engine = this.getEngine();
  22631. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  22632. if (!canvas) {
  22633. return;
  22634. }
  22635. canvas.addEventListener("keydown", _this._onKeyDown, false);
  22636. canvas.addEventListener("keyup", _this._onKeyUp, false);
  22637. });
  22638. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  22639. if (!canvas) {
  22640. return;
  22641. }
  22642. canvas.removeEventListener("keydown", _this._onKeyDown);
  22643. canvas.removeEventListener("keyup", _this._onKeyUp);
  22644. });
  22645. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22646. var canvas = this._engine.getRenderingCanvas();
  22647. if (!canvas) {
  22648. return;
  22649. }
  22650. if (attachMove) {
  22651. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  22652. // Wheel
  22653. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  22654. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  22655. }
  22656. if (attachDown) {
  22657. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  22658. }
  22659. if (attachUp) {
  22660. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  22661. }
  22662. canvas.tabIndex = 1;
  22663. };
  22664. Scene.prototype.detachControl = function () {
  22665. var engine = this.getEngine();
  22666. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22667. var canvas = engine.getRenderingCanvas();
  22668. if (!canvas) {
  22669. return;
  22670. }
  22671. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  22672. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  22673. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  22674. if (this._onCanvasBlurObserver) {
  22675. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  22676. }
  22677. if (this._onCanvasFocusObserver) {
  22678. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  22679. }
  22680. // Wheel
  22681. canvas.removeEventListener('mousewheel', this._onPointerMove);
  22682. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  22683. // Keyboard
  22684. canvas.removeEventListener("keydown", this._onKeyDown);
  22685. canvas.removeEventListener("keyup", this._onKeyUp);
  22686. // Observables
  22687. this.onKeyboardObservable.clear();
  22688. this.onPreKeyboardObservable.clear();
  22689. this.onPointerObservable.clear();
  22690. this.onPrePointerObservable.clear();
  22691. };
  22692. /**
  22693. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  22694. * Delay loaded resources are not taking in account
  22695. * @return true if all required resources are ready
  22696. */
  22697. Scene.prototype.isReady = function () {
  22698. if (this._isDisposed) {
  22699. return false;
  22700. }
  22701. if (this._pendingData.length > 0) {
  22702. return false;
  22703. }
  22704. var index;
  22705. var engine = this.getEngine();
  22706. // Geometries
  22707. for (index = 0; index < this._geometries.length; index++) {
  22708. var geometry = this._geometries[index];
  22709. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22710. return false;
  22711. }
  22712. }
  22713. // Meshes
  22714. for (index = 0; index < this.meshes.length; index++) {
  22715. var mesh = this.meshes[index];
  22716. if (!mesh.isEnabled()) {
  22717. continue;
  22718. }
  22719. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  22720. continue;
  22721. }
  22722. if (!mesh.isReady(true)) {
  22723. return false;
  22724. }
  22725. // Effect layers
  22726. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  22727. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  22728. var layer = _a[_i];
  22729. if (!layer.hasMesh(mesh)) {
  22730. continue;
  22731. }
  22732. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22733. var subMesh = _c[_b];
  22734. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  22735. return false;
  22736. }
  22737. }
  22738. }
  22739. }
  22740. return true;
  22741. };
  22742. Scene.prototype.resetCachedMaterial = function () {
  22743. this._cachedMaterial = null;
  22744. this._cachedEffect = null;
  22745. this._cachedVisibility = null;
  22746. };
  22747. Scene.prototype.registerBeforeRender = function (func) {
  22748. this.onBeforeRenderObservable.add(func);
  22749. };
  22750. Scene.prototype.unregisterBeforeRender = function (func) {
  22751. this.onBeforeRenderObservable.removeCallback(func);
  22752. };
  22753. Scene.prototype.registerAfterRender = function (func) {
  22754. this.onAfterRenderObservable.add(func);
  22755. };
  22756. Scene.prototype.unregisterAfterRender = function (func) {
  22757. this.onAfterRenderObservable.removeCallback(func);
  22758. };
  22759. Scene.prototype._executeOnceBeforeRender = function (func) {
  22760. var _this = this;
  22761. var execFunc = function () {
  22762. func();
  22763. setTimeout(function () {
  22764. _this.unregisterBeforeRender(execFunc);
  22765. });
  22766. };
  22767. this.registerBeforeRender(execFunc);
  22768. };
  22769. /**
  22770. * The provided function will run before render once and will be disposed afterwards.
  22771. * A timeout delay can be provided so that the function will be executed in N ms.
  22772. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  22773. * @param func The function to be executed.
  22774. * @param timeout optional delay in ms
  22775. */
  22776. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  22777. var _this = this;
  22778. if (timeout !== undefined) {
  22779. setTimeout(function () {
  22780. _this._executeOnceBeforeRender(func);
  22781. }, timeout);
  22782. }
  22783. else {
  22784. this._executeOnceBeforeRender(func);
  22785. }
  22786. };
  22787. Scene.prototype._addPendingData = function (data) {
  22788. this._pendingData.push(data);
  22789. };
  22790. Scene.prototype._removePendingData = function (data) {
  22791. var wasLoading = this.isLoading;
  22792. var index = this._pendingData.indexOf(data);
  22793. if (index !== -1) {
  22794. this._pendingData.splice(index, 1);
  22795. }
  22796. if (wasLoading && !this.isLoading) {
  22797. this.onDataLoadedObservable.notifyObservers(this);
  22798. }
  22799. };
  22800. Scene.prototype.getWaitingItemsCount = function () {
  22801. return this._pendingData.length;
  22802. };
  22803. Object.defineProperty(Scene.prototype, "isLoading", {
  22804. get: function () {
  22805. return this._pendingData.length > 0;
  22806. },
  22807. enumerable: true,
  22808. configurable: true
  22809. });
  22810. /**
  22811. * Registers a function to be executed when the scene is ready.
  22812. * @param {Function} func - the function to be executed.
  22813. */
  22814. Scene.prototype.executeWhenReady = function (func) {
  22815. var _this = this;
  22816. this.onReadyObservable.add(func);
  22817. if (this._executeWhenReadyTimeoutId !== -1) {
  22818. return;
  22819. }
  22820. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22821. _this._checkIsReady();
  22822. }, 150);
  22823. };
  22824. /**
  22825. * Returns a promise that resolves when the scene is ready.
  22826. * @returns A promise that resolves when the scene is ready.
  22827. */
  22828. Scene.prototype.whenReadyAsync = function () {
  22829. var _this = this;
  22830. return new Promise(function (resolve) {
  22831. _this.executeWhenReady(function () {
  22832. resolve();
  22833. });
  22834. });
  22835. };
  22836. Scene.prototype._checkIsReady = function () {
  22837. var _this = this;
  22838. if (this.isReady()) {
  22839. this.onReadyObservable.notifyObservers(this);
  22840. this.onReadyObservable.clear();
  22841. this._executeWhenReadyTimeoutId = -1;
  22842. return;
  22843. }
  22844. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22845. _this._checkIsReady();
  22846. }, 150);
  22847. };
  22848. // Animations
  22849. /**
  22850. * Will start the animation sequence of a given target
  22851. * @param target - the target
  22852. * @param {number} from - from which frame should animation start
  22853. * @param {number} to - till which frame should animation run.
  22854. * @param {boolean} [loop] - should the animation loop
  22855. * @param {number} [speedRatio] - the speed in which to run the animation
  22856. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  22857. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  22858. * Returns {BABYLON.Animatable} the animatable object created for this animation
  22859. * See BABYLON.Animatable
  22860. */
  22861. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  22862. if (speedRatio === void 0) { speedRatio = 1.0; }
  22863. if (from > to && speedRatio > 0) {
  22864. speedRatio *= -1;
  22865. }
  22866. this.stopAnimation(target);
  22867. if (!animatable) {
  22868. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  22869. }
  22870. // Local animations
  22871. if (target.animations) {
  22872. animatable.appendAnimations(target, target.animations);
  22873. }
  22874. // Children animations
  22875. if (target.getAnimatables) {
  22876. var animatables = target.getAnimatables();
  22877. for (var index = 0; index < animatables.length; index++) {
  22878. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  22879. }
  22880. }
  22881. animatable.reset();
  22882. return animatable;
  22883. };
  22884. /**
  22885. * Begin a new animation on a given node
  22886. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22887. * @param {BABYLON.Animation[]} defines the list of animations to start
  22888. * @param {number} from defines the initial value
  22889. * @param {number} to defines the final value
  22890. * @param {boolean} loop defines if you want animation to loop (off by default)
  22891. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22892. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22893. * @returns the list of created animatables
  22894. */
  22895. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22896. if (speedRatio === undefined) {
  22897. speedRatio = 1.0;
  22898. }
  22899. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  22900. return animatable;
  22901. };
  22902. /**
  22903. * Begin a new animation on a given node and its hierarchy
  22904. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22905. * @param {boolean} 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.
  22906. * @param {BABYLON.Animation[]} defines the list of animations to start
  22907. * @param {number} from defines the initial value
  22908. * @param {number} to defines the final value
  22909. * @param {boolean} loop defines if you want animation to loop (off by default)
  22910. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22911. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22912. * @returns the list of animatables created for all nodes
  22913. */
  22914. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22915. var children = target.getDescendants(directDescendantsOnly);
  22916. var result = [];
  22917. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  22918. var child = children_1[_i];
  22919. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  22920. }
  22921. return result;
  22922. };
  22923. Scene.prototype.getAnimatableByTarget = function (target) {
  22924. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22925. if (this._activeAnimatables[index].target === target) {
  22926. return this._activeAnimatables[index];
  22927. }
  22928. }
  22929. return null;
  22930. };
  22931. Object.defineProperty(Scene.prototype, "animatables", {
  22932. get: function () {
  22933. return this._activeAnimatables;
  22934. },
  22935. enumerable: true,
  22936. configurable: true
  22937. });
  22938. /**
  22939. * Will stop the animation of the given target
  22940. * @param target - the target
  22941. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  22942. * @see beginAnimation
  22943. */
  22944. Scene.prototype.stopAnimation = function (target, animationName) {
  22945. var animatable = this.getAnimatableByTarget(target);
  22946. if (animatable) {
  22947. animatable.stop(animationName);
  22948. }
  22949. };
  22950. /**
  22951. * Stops and removes all animations that have been applied to the scene
  22952. */
  22953. Scene.prototype.stopAllAnimations = function () {
  22954. if (this._activeAnimatables) {
  22955. for (var i = 0; i < this._activeAnimatables.length; i++) {
  22956. this._activeAnimatables[i].stop();
  22957. }
  22958. this._activeAnimatables = [];
  22959. }
  22960. };
  22961. Scene.prototype._animate = function () {
  22962. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  22963. return;
  22964. }
  22965. // Getting time
  22966. var now = BABYLON.Tools.Now;
  22967. if (!this._animationTimeLast) {
  22968. if (this._pendingData.length > 0) {
  22969. return;
  22970. }
  22971. this._animationTimeLast = now;
  22972. }
  22973. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  22974. this._animationTime += deltaTime;
  22975. this._animationTimeLast = now;
  22976. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22977. this._activeAnimatables[index]._animate(this._animationTime);
  22978. }
  22979. };
  22980. // Matrix
  22981. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  22982. this._useAlternateCameraConfiguration = active;
  22983. };
  22984. Scene.prototype.getViewMatrix = function () {
  22985. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  22986. };
  22987. Scene.prototype.getProjectionMatrix = function () {
  22988. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  22989. };
  22990. Scene.prototype.getTransformMatrix = function () {
  22991. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  22992. };
  22993. Scene.prototype.setTransformMatrix = function (view, projection) {
  22994. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  22995. return;
  22996. }
  22997. this._viewUpdateFlag = view.updateFlag;
  22998. this._projectionUpdateFlag = projection.updateFlag;
  22999. this._viewMatrix = view;
  23000. this._projectionMatrix = projection;
  23001. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23002. // Update frustum
  23003. if (!this._frustumPlanes) {
  23004. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23005. }
  23006. else {
  23007. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23008. }
  23009. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23010. var otherCamera = this.activeCamera._alternateCamera;
  23011. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23012. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23013. }
  23014. if (this._sceneUbo.useUbo) {
  23015. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23016. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23017. this._sceneUbo.update();
  23018. }
  23019. };
  23020. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23021. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23022. return;
  23023. }
  23024. this._alternateViewUpdateFlag = view.updateFlag;
  23025. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23026. this._alternateViewMatrix = view;
  23027. this._alternateProjectionMatrix = projection;
  23028. if (!this._alternateTransformMatrix) {
  23029. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23030. }
  23031. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23032. if (!this._alternateSceneUbo) {
  23033. this._createAlternateUbo();
  23034. }
  23035. if (this._alternateSceneUbo.useUbo) {
  23036. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23037. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23038. this._alternateSceneUbo.update();
  23039. }
  23040. };
  23041. Scene.prototype.getSceneUniformBuffer = function () {
  23042. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23043. };
  23044. // Methods
  23045. Scene.prototype.getUniqueId = function () {
  23046. var result = Scene._uniqueIdCounter;
  23047. Scene._uniqueIdCounter++;
  23048. return result;
  23049. };
  23050. Scene.prototype.addMesh = function (newMesh) {
  23051. this.meshes.push(newMesh);
  23052. //notify the collision coordinator
  23053. if (this.collisionCoordinator) {
  23054. this.collisionCoordinator.onMeshAdded(newMesh);
  23055. }
  23056. newMesh._resyncLightSources();
  23057. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23058. };
  23059. Scene.prototype.removeMesh = function (toRemove) {
  23060. var index = this.meshes.indexOf(toRemove);
  23061. if (index !== -1) {
  23062. // Remove from the scene if mesh found
  23063. this.meshes.splice(index, 1);
  23064. }
  23065. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23066. return index;
  23067. };
  23068. Scene.prototype.addTransformNode = function (newTransformNode) {
  23069. this.transformNodes.push(newTransformNode);
  23070. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23071. };
  23072. Scene.prototype.removeTransformNode = function (toRemove) {
  23073. var index = this.transformNodes.indexOf(toRemove);
  23074. if (index !== -1) {
  23075. // Remove from the scene if found
  23076. this.transformNodes.splice(index, 1);
  23077. }
  23078. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23079. return index;
  23080. };
  23081. Scene.prototype.removeSkeleton = function (toRemove) {
  23082. var index = this.skeletons.indexOf(toRemove);
  23083. if (index !== -1) {
  23084. // Remove from the scene if found
  23085. this.skeletons.splice(index, 1);
  23086. }
  23087. return index;
  23088. };
  23089. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23090. var index = this.morphTargetManagers.indexOf(toRemove);
  23091. if (index !== -1) {
  23092. // Remove from the scene if found
  23093. this.morphTargetManagers.splice(index, 1);
  23094. }
  23095. return index;
  23096. };
  23097. Scene.prototype.removeLight = function (toRemove) {
  23098. var index = this.lights.indexOf(toRemove);
  23099. if (index !== -1) {
  23100. // Remove from meshes
  23101. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23102. var mesh = _a[_i];
  23103. mesh._removeLightSource(toRemove);
  23104. }
  23105. // Remove from the scene if mesh found
  23106. this.lights.splice(index, 1);
  23107. this.sortLightsByPriority();
  23108. }
  23109. this.onLightRemovedObservable.notifyObservers(toRemove);
  23110. return index;
  23111. };
  23112. Scene.prototype.removeCamera = function (toRemove) {
  23113. var index = this.cameras.indexOf(toRemove);
  23114. if (index !== -1) {
  23115. // Remove from the scene if mesh found
  23116. this.cameras.splice(index, 1);
  23117. }
  23118. // Remove from activeCameras
  23119. var index2 = this.activeCameras.indexOf(toRemove);
  23120. if (index2 !== -1) {
  23121. // Remove from the scene if mesh found
  23122. this.activeCameras.splice(index2, 1);
  23123. }
  23124. // Reset the activeCamera
  23125. if (this.activeCamera === toRemove) {
  23126. if (this.cameras.length > 0) {
  23127. this.activeCamera = this.cameras[0];
  23128. }
  23129. else {
  23130. this.activeCamera = null;
  23131. }
  23132. }
  23133. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23134. return index;
  23135. };
  23136. Scene.prototype.removeParticleSystem = function (toRemove) {
  23137. var index = this.particleSystems.indexOf(toRemove);
  23138. if (index !== -1) {
  23139. this.particleSystems.splice(index, 1);
  23140. }
  23141. return index;
  23142. };
  23143. ;
  23144. Scene.prototype.removeAnimation = function (toRemove) {
  23145. var index = this.animations.indexOf(toRemove);
  23146. if (index !== -1) {
  23147. this.animations.splice(index, 1);
  23148. }
  23149. return index;
  23150. };
  23151. ;
  23152. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23153. var index = this.multiMaterials.indexOf(toRemove);
  23154. if (index !== -1) {
  23155. this.multiMaterials.splice(index, 1);
  23156. }
  23157. return index;
  23158. };
  23159. ;
  23160. Scene.prototype.removeMaterial = function (toRemove) {
  23161. var index = this.materials.indexOf(toRemove);
  23162. if (index !== -1) {
  23163. this.materials.splice(index, 1);
  23164. }
  23165. return index;
  23166. };
  23167. ;
  23168. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23169. var index = this.lensFlareSystems.indexOf(toRemove);
  23170. if (index !== -1) {
  23171. this.lensFlareSystems.splice(index, 1);
  23172. }
  23173. return index;
  23174. };
  23175. ;
  23176. Scene.prototype.removeActionManager = function (toRemove) {
  23177. var index = this._actionManagers.indexOf(toRemove);
  23178. if (index !== -1) {
  23179. this._actionManagers.splice(index, 1);
  23180. }
  23181. return index;
  23182. };
  23183. ;
  23184. Scene.prototype.addLight = function (newLight) {
  23185. this.lights.push(newLight);
  23186. this.sortLightsByPriority();
  23187. // Add light to all meshes (To support if the light is removed and then readded)
  23188. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23189. var mesh = _a[_i];
  23190. if (mesh._lightSources.indexOf(newLight) === -1) {
  23191. mesh._lightSources.push(newLight);
  23192. mesh._resyncLightSources();
  23193. }
  23194. }
  23195. this.onNewLightAddedObservable.notifyObservers(newLight);
  23196. };
  23197. Scene.prototype.sortLightsByPriority = function () {
  23198. if (this.requireLightSorting) {
  23199. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23200. }
  23201. };
  23202. Scene.prototype.addCamera = function (newCamera) {
  23203. this.cameras.push(newCamera);
  23204. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23205. };
  23206. Scene.prototype.addSkeleton = function (newSkeleton) {
  23207. this.skeletons.push(newSkeleton);
  23208. };
  23209. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23210. this.particleSystems.push(newParticleSystem);
  23211. };
  23212. Scene.prototype.addAnimation = function (newAnimation) {
  23213. this.animations.push(newAnimation);
  23214. };
  23215. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23216. this.multiMaterials.push(newMultiMaterial);
  23217. };
  23218. Scene.prototype.addMaterial = function (newMaterial) {
  23219. this.materials.push(newMaterial);
  23220. };
  23221. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23222. this.morphTargetManagers.push(newMorphTargetManager);
  23223. };
  23224. Scene.prototype.addGeometry = function (newGeometrie) {
  23225. this._geometries.push(newGeometrie);
  23226. };
  23227. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23228. this.lensFlareSystems.push(newLensFlareSystem);
  23229. };
  23230. Scene.prototype.addActionManager = function (newActionManager) {
  23231. this._actionManagers.push(newActionManager);
  23232. };
  23233. /**
  23234. * Switch active camera
  23235. * @param {Camera} newCamera - new active camera
  23236. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23237. */
  23238. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23239. if (attachControl === void 0) { attachControl = true; }
  23240. var canvas = this._engine.getRenderingCanvas();
  23241. if (!canvas) {
  23242. return;
  23243. }
  23244. if (this.activeCamera) {
  23245. this.activeCamera.detachControl(canvas);
  23246. }
  23247. this.activeCamera = newCamera;
  23248. if (attachControl) {
  23249. newCamera.attachControl(canvas);
  23250. }
  23251. };
  23252. /**
  23253. * sets the active camera of the scene using its ID
  23254. * @param {string} id - the camera's ID
  23255. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23256. * @see activeCamera
  23257. */
  23258. Scene.prototype.setActiveCameraByID = function (id) {
  23259. var camera = this.getCameraByID(id);
  23260. if (camera) {
  23261. this.activeCamera = camera;
  23262. return camera;
  23263. }
  23264. return null;
  23265. };
  23266. /**
  23267. * sets the active camera of the scene using its name
  23268. * @param {string} name - the camera's name
  23269. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23270. * @see activeCamera
  23271. */
  23272. Scene.prototype.setActiveCameraByName = function (name) {
  23273. var camera = this.getCameraByName(name);
  23274. if (camera) {
  23275. this.activeCamera = camera;
  23276. return camera;
  23277. }
  23278. return null;
  23279. };
  23280. /**
  23281. * get an animation group using its name
  23282. * @param {string} the material's name
  23283. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23284. */
  23285. Scene.prototype.getAnimationGroupByName = function (name) {
  23286. for (var index = 0; index < this.animationGroups.length; index++) {
  23287. if (this.animationGroups[index].name === name) {
  23288. return this.animationGroups[index];
  23289. }
  23290. }
  23291. return null;
  23292. };
  23293. /**
  23294. * get a material using its id
  23295. * @param {string} the material's ID
  23296. * @return {BABYLON.Material|null} the material or null if none found.
  23297. */
  23298. Scene.prototype.getMaterialByID = function (id) {
  23299. for (var index = 0; index < this.materials.length; index++) {
  23300. if (this.materials[index].id === id) {
  23301. return this.materials[index];
  23302. }
  23303. }
  23304. return null;
  23305. };
  23306. /**
  23307. * get a material using its name
  23308. * @param {string} the material's name
  23309. * @return {BABYLON.Material|null} the material or null if none found.
  23310. */
  23311. Scene.prototype.getMaterialByName = function (name) {
  23312. for (var index = 0; index < this.materials.length; index++) {
  23313. if (this.materials[index].name === name) {
  23314. return this.materials[index];
  23315. }
  23316. }
  23317. return null;
  23318. };
  23319. Scene.prototype.getLensFlareSystemByName = function (name) {
  23320. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23321. if (this.lensFlareSystems[index].name === name) {
  23322. return this.lensFlareSystems[index];
  23323. }
  23324. }
  23325. return null;
  23326. };
  23327. Scene.prototype.getLensFlareSystemByID = function (id) {
  23328. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23329. if (this.lensFlareSystems[index].id === id) {
  23330. return this.lensFlareSystems[index];
  23331. }
  23332. }
  23333. return null;
  23334. };
  23335. Scene.prototype.getCameraByID = function (id) {
  23336. for (var index = 0; index < this.cameras.length; index++) {
  23337. if (this.cameras[index].id === id) {
  23338. return this.cameras[index];
  23339. }
  23340. }
  23341. return null;
  23342. };
  23343. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23344. for (var index = 0; index < this.cameras.length; index++) {
  23345. if (this.cameras[index].uniqueId === uniqueId) {
  23346. return this.cameras[index];
  23347. }
  23348. }
  23349. return null;
  23350. };
  23351. /**
  23352. * get a camera using its name
  23353. * @param {string} the camera's name
  23354. * @return {BABYLON.Camera|null} the camera or null if none found.
  23355. */
  23356. Scene.prototype.getCameraByName = function (name) {
  23357. for (var index = 0; index < this.cameras.length; index++) {
  23358. if (this.cameras[index].name === name) {
  23359. return this.cameras[index];
  23360. }
  23361. }
  23362. return null;
  23363. };
  23364. /**
  23365. * get a bone using its id
  23366. * @param {string} the bone's id
  23367. * @return {BABYLON.Bone|null} the bone or null if not found
  23368. */
  23369. Scene.prototype.getBoneByID = function (id) {
  23370. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23371. var skeleton = this.skeletons[skeletonIndex];
  23372. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23373. if (skeleton.bones[boneIndex].id === id) {
  23374. return skeleton.bones[boneIndex];
  23375. }
  23376. }
  23377. }
  23378. return null;
  23379. };
  23380. /**
  23381. * get a bone using its id
  23382. * @param {string} the bone's name
  23383. * @return {BABYLON.Bone|null} the bone or null if not found
  23384. */
  23385. Scene.prototype.getBoneByName = function (name) {
  23386. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23387. var skeleton = this.skeletons[skeletonIndex];
  23388. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23389. if (skeleton.bones[boneIndex].name === name) {
  23390. return skeleton.bones[boneIndex];
  23391. }
  23392. }
  23393. }
  23394. return null;
  23395. };
  23396. /**
  23397. * get a light node using its name
  23398. * @param {string} the light's name
  23399. * @return {BABYLON.Light|null} the light or null if none found.
  23400. */
  23401. Scene.prototype.getLightByName = function (name) {
  23402. for (var index = 0; index < this.lights.length; index++) {
  23403. if (this.lights[index].name === name) {
  23404. return this.lights[index];
  23405. }
  23406. }
  23407. return null;
  23408. };
  23409. /**
  23410. * get a light node using its ID
  23411. * @param {string} the light's id
  23412. * @return {BABYLON.Light|null} the light or null if none found.
  23413. */
  23414. Scene.prototype.getLightByID = function (id) {
  23415. for (var index = 0; index < this.lights.length; index++) {
  23416. if (this.lights[index].id === id) {
  23417. return this.lights[index];
  23418. }
  23419. }
  23420. return null;
  23421. };
  23422. /**
  23423. * get a light node using its scene-generated unique ID
  23424. * @param {number} the light's unique id
  23425. * @return {BABYLON.Light|null} the light or null if none found.
  23426. */
  23427. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23428. for (var index = 0; index < this.lights.length; index++) {
  23429. if (this.lights[index].uniqueId === uniqueId) {
  23430. return this.lights[index];
  23431. }
  23432. }
  23433. return null;
  23434. };
  23435. /**
  23436. * get a particle system by id
  23437. * @param id {number} the particle system id
  23438. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23439. */
  23440. Scene.prototype.getParticleSystemByID = function (id) {
  23441. for (var index = 0; index < this.particleSystems.length; index++) {
  23442. if (this.particleSystems[index].id === id) {
  23443. return this.particleSystems[index];
  23444. }
  23445. }
  23446. return null;
  23447. };
  23448. /**
  23449. * get a geometry using its ID
  23450. * @param {string} the geometry's id
  23451. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23452. */
  23453. Scene.prototype.getGeometryByID = function (id) {
  23454. for (var index = 0; index < this._geometries.length; index++) {
  23455. if (this._geometries[index].id === id) {
  23456. return this._geometries[index];
  23457. }
  23458. }
  23459. return null;
  23460. };
  23461. /**
  23462. * add a new geometry to this scene.
  23463. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23464. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23465. * @return {boolean} was the geometry added or not
  23466. */
  23467. Scene.prototype.pushGeometry = function (geometry, force) {
  23468. if (!force && this.getGeometryByID(geometry.id)) {
  23469. return false;
  23470. }
  23471. this._geometries.push(geometry);
  23472. //notify the collision coordinator
  23473. if (this.collisionCoordinator) {
  23474. this.collisionCoordinator.onGeometryAdded(geometry);
  23475. }
  23476. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  23477. return true;
  23478. };
  23479. /**
  23480. * Removes an existing geometry
  23481. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  23482. * @return {boolean} was the geometry removed or not
  23483. */
  23484. Scene.prototype.removeGeometry = function (geometry) {
  23485. var index = this._geometries.indexOf(geometry);
  23486. if (index > -1) {
  23487. this._geometries.splice(index, 1);
  23488. //notify the collision coordinator
  23489. if (this.collisionCoordinator) {
  23490. this.collisionCoordinator.onGeometryDeleted(geometry);
  23491. }
  23492. this.onGeometryRemovedObservable.notifyObservers(geometry);
  23493. return true;
  23494. }
  23495. return false;
  23496. };
  23497. Scene.prototype.getGeometries = function () {
  23498. return this._geometries;
  23499. };
  23500. /**
  23501. * Get the first added mesh found of a given ID
  23502. * @param {string} id - the id to search for
  23503. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23504. */
  23505. Scene.prototype.getMeshByID = function (id) {
  23506. for (var index = 0; index < this.meshes.length; index++) {
  23507. if (this.meshes[index].id === id) {
  23508. return this.meshes[index];
  23509. }
  23510. }
  23511. return null;
  23512. };
  23513. Scene.prototype.getMeshesByID = function (id) {
  23514. return this.meshes.filter(function (m) {
  23515. return m.id === id;
  23516. });
  23517. };
  23518. /**
  23519. * Get the first added transform node found of a given ID
  23520. * @param {string} id - the id to search for
  23521. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  23522. */
  23523. Scene.prototype.getTransformNodeByID = function (id) {
  23524. for (var index = 0; index < this.transformNodes.length; index++) {
  23525. if (this.transformNodes[index].id === id) {
  23526. return this.transformNodes[index];
  23527. }
  23528. }
  23529. return null;
  23530. };
  23531. Scene.prototype.getTransformNodesByID = function (id) {
  23532. return this.transformNodes.filter(function (m) {
  23533. return m.id === id;
  23534. });
  23535. };
  23536. /**
  23537. * Get a mesh with its auto-generated unique id
  23538. * @param {number} uniqueId - the unique id to search for
  23539. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23540. */
  23541. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  23542. for (var index = 0; index < this.meshes.length; index++) {
  23543. if (this.meshes[index].uniqueId === uniqueId) {
  23544. return this.meshes[index];
  23545. }
  23546. }
  23547. return null;
  23548. };
  23549. /**
  23550. * Get a the last added mesh found of a given ID
  23551. * @param {string} id - the id to search for
  23552. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23553. */
  23554. Scene.prototype.getLastMeshByID = function (id) {
  23555. for (var index = this.meshes.length - 1; index >= 0; index--) {
  23556. if (this.meshes[index].id === id) {
  23557. return this.meshes[index];
  23558. }
  23559. }
  23560. return null;
  23561. };
  23562. /**
  23563. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  23564. * @param {string} id - the id to search for
  23565. * @return {BABYLON.Node|null} the node found or null if not found at all.
  23566. */
  23567. Scene.prototype.getLastEntryByID = function (id) {
  23568. var index;
  23569. for (index = this.meshes.length - 1; index >= 0; index--) {
  23570. if (this.meshes[index].id === id) {
  23571. return this.meshes[index];
  23572. }
  23573. }
  23574. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  23575. if (this.transformNodes[index].id === id) {
  23576. return this.transformNodes[index];
  23577. }
  23578. }
  23579. for (index = this.cameras.length - 1; index >= 0; index--) {
  23580. if (this.cameras[index].id === id) {
  23581. return this.cameras[index];
  23582. }
  23583. }
  23584. for (index = this.lights.length - 1; index >= 0; index--) {
  23585. if (this.lights[index].id === id) {
  23586. return this.lights[index];
  23587. }
  23588. }
  23589. return null;
  23590. };
  23591. Scene.prototype.getNodeByID = function (id) {
  23592. var mesh = this.getMeshByID(id);
  23593. if (mesh) {
  23594. return mesh;
  23595. }
  23596. var light = this.getLightByID(id);
  23597. if (light) {
  23598. return light;
  23599. }
  23600. var camera = this.getCameraByID(id);
  23601. if (camera) {
  23602. return camera;
  23603. }
  23604. var bone = this.getBoneByID(id);
  23605. return bone;
  23606. };
  23607. Scene.prototype.getNodeByName = function (name) {
  23608. var mesh = this.getMeshByName(name);
  23609. if (mesh) {
  23610. return mesh;
  23611. }
  23612. var light = this.getLightByName(name);
  23613. if (light) {
  23614. return light;
  23615. }
  23616. var camera = this.getCameraByName(name);
  23617. if (camera) {
  23618. return camera;
  23619. }
  23620. var bone = this.getBoneByName(name);
  23621. return bone;
  23622. };
  23623. Scene.prototype.getMeshByName = function (name) {
  23624. for (var index = 0; index < this.meshes.length; index++) {
  23625. if (this.meshes[index].name === name) {
  23626. return this.meshes[index];
  23627. }
  23628. }
  23629. return null;
  23630. };
  23631. Scene.prototype.getTransformNodeByName = function (name) {
  23632. for (var index = 0; index < this.transformNodes.length; index++) {
  23633. if (this.transformNodes[index].name === name) {
  23634. return this.transformNodes[index];
  23635. }
  23636. }
  23637. return null;
  23638. };
  23639. Scene.prototype.getSoundByName = function (name) {
  23640. var index;
  23641. if (BABYLON.AudioEngine) {
  23642. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  23643. if (this.mainSoundTrack.soundCollection[index].name === name) {
  23644. return this.mainSoundTrack.soundCollection[index];
  23645. }
  23646. }
  23647. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  23648. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  23649. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  23650. return this.soundTracks[sdIndex].soundCollection[index];
  23651. }
  23652. }
  23653. }
  23654. }
  23655. return null;
  23656. };
  23657. Scene.prototype.getLastSkeletonByID = function (id) {
  23658. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  23659. if (this.skeletons[index].id === id) {
  23660. return this.skeletons[index];
  23661. }
  23662. }
  23663. return null;
  23664. };
  23665. Scene.prototype.getSkeletonById = function (id) {
  23666. for (var index = 0; index < this.skeletons.length; index++) {
  23667. if (this.skeletons[index].id === id) {
  23668. return this.skeletons[index];
  23669. }
  23670. }
  23671. return null;
  23672. };
  23673. Scene.prototype.getSkeletonByName = function (name) {
  23674. for (var index = 0; index < this.skeletons.length; index++) {
  23675. if (this.skeletons[index].name === name) {
  23676. return this.skeletons[index];
  23677. }
  23678. }
  23679. return null;
  23680. };
  23681. Scene.prototype.getMorphTargetManagerById = function (id) {
  23682. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  23683. if (this.morphTargetManagers[index].uniqueId === id) {
  23684. return this.morphTargetManagers[index];
  23685. }
  23686. }
  23687. return null;
  23688. };
  23689. Scene.prototype.isActiveMesh = function (mesh) {
  23690. return (this._activeMeshes.indexOf(mesh) !== -1);
  23691. };
  23692. /**
  23693. * Return a the first highlight layer of the scene with a given name.
  23694. * @param name The name of the highlight layer to look for.
  23695. * @return The highlight layer if found otherwise null.
  23696. */
  23697. Scene.prototype.getHighlightLayerByName = function (name) {
  23698. for (var index = 0; index < this.effectLayers.length; index++) {
  23699. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  23700. return this.effectLayers[index];
  23701. }
  23702. }
  23703. return null;
  23704. };
  23705. /**
  23706. * Return a the first highlight layer of the scene with a given name.
  23707. * @param name The name of the highlight layer to look for.
  23708. * @return The highlight layer if found otherwise null.
  23709. */
  23710. Scene.prototype.getGlowLayerByName = function (name) {
  23711. for (var index = 0; index < this.effectLayers.length; index++) {
  23712. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  23713. return this.effectLayers[index];
  23714. }
  23715. }
  23716. return null;
  23717. };
  23718. Object.defineProperty(Scene.prototype, "uid", {
  23719. /**
  23720. * Return a unique id as a string which can serve as an identifier for the scene
  23721. */
  23722. get: function () {
  23723. if (!this._uid) {
  23724. this._uid = BABYLON.Tools.RandomId();
  23725. }
  23726. return this._uid;
  23727. },
  23728. enumerable: true,
  23729. configurable: true
  23730. });
  23731. /**
  23732. * Add an externaly attached data from its key.
  23733. * This method call will fail and return false, if such key already exists.
  23734. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  23735. * @param key the unique key that identifies the data
  23736. * @param data the data object to associate to the key for this Engine instance
  23737. * @return true if no such key were already present and the data was added successfully, false otherwise
  23738. */
  23739. Scene.prototype.addExternalData = function (key, data) {
  23740. if (!this._externalData) {
  23741. this._externalData = new BABYLON.StringDictionary();
  23742. }
  23743. return this._externalData.add(key, data);
  23744. };
  23745. /**
  23746. * Get an externaly attached data from its key
  23747. * @param key the unique key that identifies the data
  23748. * @return the associated data, if present (can be null), or undefined if not present
  23749. */
  23750. Scene.prototype.getExternalData = function (key) {
  23751. if (!this._externalData) {
  23752. return null;
  23753. }
  23754. return this._externalData.get(key);
  23755. };
  23756. /**
  23757. * Get an externaly attached data from its key, create it using a factory if it's not already present
  23758. * @param key the unique key that identifies the data
  23759. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  23760. * @return the associated data, can be null if the factory returned null.
  23761. */
  23762. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  23763. if (!this._externalData) {
  23764. this._externalData = new BABYLON.StringDictionary();
  23765. }
  23766. return this._externalData.getOrAddWithFactory(key, factory);
  23767. };
  23768. /**
  23769. * Remove an externaly attached data from the Engine instance
  23770. * @param key the unique key that identifies the data
  23771. * @return true if the data was successfully removed, false if it doesn't exist
  23772. */
  23773. Scene.prototype.removeExternalData = function (key) {
  23774. return this._externalData.remove(key);
  23775. };
  23776. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  23777. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  23778. if (mesh.showSubMeshesBoundingBox) {
  23779. var boundingInfo = subMesh.getBoundingInfo();
  23780. if (boundingInfo !== null && boundingInfo !== undefined) {
  23781. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23782. }
  23783. }
  23784. var material = subMesh.getMaterial();
  23785. if (material !== null && material !== undefined) {
  23786. // Render targets
  23787. if (material.getRenderTargetTextures !== undefined) {
  23788. if (this._processedMaterials.indexOf(material) === -1) {
  23789. this._processedMaterials.push(material);
  23790. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  23791. }
  23792. }
  23793. // Dispatch
  23794. this._activeIndices.addCount(subMesh.indexCount, false);
  23795. this._renderingManager.dispatch(subMesh, mesh, material);
  23796. }
  23797. }
  23798. };
  23799. Scene.prototype._isInIntermediateRendering = function () {
  23800. return this._intermediateRendering;
  23801. };
  23802. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  23803. this._activeMeshCandidateProvider = provider;
  23804. };
  23805. Scene.prototype.getActiveMeshCandidateProvider = function () {
  23806. return this._activeMeshCandidateProvider;
  23807. };
  23808. /**
  23809. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  23810. */
  23811. Scene.prototype.freezeActiveMeshes = function () {
  23812. this._evaluateActiveMeshes();
  23813. this._activeMeshesFrozen = true;
  23814. return this;
  23815. };
  23816. /**
  23817. * Use this function to restart evaluating active meshes on every frame
  23818. */
  23819. Scene.prototype.unfreezeActiveMeshes = function () {
  23820. this._activeMeshesFrozen = false;
  23821. return this;
  23822. };
  23823. Scene.prototype._evaluateActiveMeshes = function () {
  23824. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  23825. return;
  23826. }
  23827. if (!this.activeCamera) {
  23828. return;
  23829. }
  23830. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  23831. this.activeCamera._activeMeshes.reset();
  23832. this._activeMeshes.reset();
  23833. this._renderingManager.reset();
  23834. this._processedMaterials.reset();
  23835. this._activeParticleSystems.reset();
  23836. this._activeSkeletons.reset();
  23837. this._softwareSkinnedMeshes.reset();
  23838. if (this._boundingBoxRenderer) {
  23839. this._boundingBoxRenderer.reset();
  23840. }
  23841. // Meshes
  23842. var meshes;
  23843. var len;
  23844. var checkIsEnabled = true;
  23845. // Determine mesh candidates
  23846. if (this._activeMeshCandidateProvider !== undefined) {
  23847. // Use _activeMeshCandidateProvider
  23848. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  23849. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  23850. if (meshes !== undefined) {
  23851. len = meshes.length;
  23852. }
  23853. else {
  23854. len = 0;
  23855. }
  23856. }
  23857. else if (this._selectionOctree !== undefined) {
  23858. // Octree
  23859. var selection = this._selectionOctree.select(this._frustumPlanes);
  23860. meshes = selection.data;
  23861. len = selection.length;
  23862. }
  23863. else {
  23864. // Full scene traversal
  23865. len = this.meshes.length;
  23866. meshes = this.meshes;
  23867. }
  23868. // Check each mesh
  23869. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  23870. mesh = meshes[meshIndex];
  23871. if (mesh.isBlocked) {
  23872. continue;
  23873. }
  23874. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  23875. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  23876. continue;
  23877. }
  23878. mesh.computeWorldMatrix();
  23879. // Intersections
  23880. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  23881. this._meshesForIntersections.pushNoDuplicate(mesh);
  23882. }
  23883. // Switch to current LOD
  23884. meshLOD = mesh.getLOD(this.activeCamera);
  23885. if (meshLOD === undefined || meshLOD === null) {
  23886. continue;
  23887. }
  23888. mesh._preActivate();
  23889. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  23890. this._activeMeshes.push(mesh);
  23891. this.activeCamera._activeMeshes.push(mesh);
  23892. mesh._activate(this._renderId);
  23893. if (meshLOD !== mesh) {
  23894. meshLOD._activate(this._renderId);
  23895. }
  23896. this._activeMesh(mesh, meshLOD);
  23897. }
  23898. }
  23899. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  23900. // Particle systems
  23901. if (this.particlesEnabled) {
  23902. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  23903. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  23904. var particleSystem = this.particleSystems[particleIndex];
  23905. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  23906. continue;
  23907. }
  23908. var emitter = particleSystem.emitter;
  23909. if (!emitter.position || emitter.isEnabled()) {
  23910. this._activeParticleSystems.push(particleSystem);
  23911. particleSystem.animate();
  23912. this._renderingManager.dispatchParticles(particleSystem);
  23913. }
  23914. }
  23915. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  23916. }
  23917. };
  23918. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  23919. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  23920. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  23921. mesh.skeleton.prepare();
  23922. }
  23923. if (!mesh.computeBonesUsingShaders) {
  23924. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  23925. }
  23926. }
  23927. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  23928. var boundingInfo = sourceMesh.getBoundingInfo();
  23929. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23930. }
  23931. if (mesh !== undefined && mesh !== null
  23932. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  23933. // Submeshes Octrees
  23934. var len;
  23935. var subMeshes;
  23936. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  23937. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  23938. len = intersections.length;
  23939. subMeshes = intersections.data;
  23940. }
  23941. else {
  23942. subMeshes = mesh.subMeshes;
  23943. len = subMeshes.length;
  23944. }
  23945. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  23946. subMesh = subMeshes[subIndex];
  23947. this._evaluateSubMesh(subMesh, mesh);
  23948. }
  23949. }
  23950. };
  23951. Scene.prototype.updateTransformMatrix = function (force) {
  23952. if (!this.activeCamera) {
  23953. return;
  23954. }
  23955. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  23956. };
  23957. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  23958. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  23959. };
  23960. Scene.prototype._renderForCamera = function (camera, rigParent) {
  23961. if (camera && camera._skipRendering) {
  23962. return;
  23963. }
  23964. var engine = this._engine;
  23965. this.activeCamera = camera;
  23966. if (!this.activeCamera)
  23967. throw new Error("Active camera not set");
  23968. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  23969. // Viewport
  23970. engine.setViewport(this.activeCamera.viewport);
  23971. // Camera
  23972. this.resetCachedMaterial();
  23973. this._renderId++;
  23974. this.updateTransformMatrix();
  23975. if (camera._alternateCamera) {
  23976. this.updateAlternateTransformMatrix(camera._alternateCamera);
  23977. this._alternateRendering = true;
  23978. }
  23979. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  23980. // Meshes
  23981. this._evaluateActiveMeshes();
  23982. // Software skinning
  23983. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  23984. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  23985. mesh.applySkeleton(mesh.skeleton);
  23986. }
  23987. // Render targets
  23988. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  23989. var needsRestoreFrameBuffer = false;
  23990. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  23991. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  23992. }
  23993. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  23994. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  23995. }
  23996. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  23997. this._intermediateRendering = true;
  23998. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  23999. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24000. var renderTarget = this._renderTargets.data[renderIndex];
  24001. if (renderTarget._shouldRender()) {
  24002. this._renderId++;
  24003. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24004. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24005. }
  24006. }
  24007. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24008. this._intermediateRendering = false;
  24009. this._renderId++;
  24010. needsRestoreFrameBuffer = true; // Restore back buffer
  24011. }
  24012. // Render EffecttLayer Texture
  24013. var stencilState = this._engine.getStencilBuffer();
  24014. var renderEffects = false;
  24015. var needStencil = false;
  24016. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24017. this._intermediateRendering = true;
  24018. for (var i = 0; i < this.effectLayers.length; i++) {
  24019. var effectLayer = this.effectLayers[i];
  24020. if (effectLayer.shouldRender() &&
  24021. (!effectLayer.camera ||
  24022. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24023. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24024. renderEffects = true;
  24025. needStencil = needStencil || effectLayer.needStencil();
  24026. var renderTarget = effectLayer._mainTexture;
  24027. if (renderTarget._shouldRender()) {
  24028. this._renderId++;
  24029. renderTarget.render(false, false);
  24030. needsRestoreFrameBuffer = true;
  24031. }
  24032. }
  24033. }
  24034. this._intermediateRendering = false;
  24035. this._renderId++;
  24036. }
  24037. if (needsRestoreFrameBuffer) {
  24038. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24039. }
  24040. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24041. // Prepare Frame
  24042. this.postProcessManager._prepareFrame();
  24043. // Backgrounds
  24044. var layerIndex;
  24045. var layer;
  24046. if (this.layers.length) {
  24047. engine.setDepthBuffer(false);
  24048. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24049. layer = this.layers[layerIndex];
  24050. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24051. layer.render();
  24052. }
  24053. }
  24054. engine.setDepthBuffer(true);
  24055. }
  24056. // Activate effect Layer stencil
  24057. if (needStencil) {
  24058. this._engine.setStencilBuffer(true);
  24059. }
  24060. // Render
  24061. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24062. this._renderingManager.render(null, null, true, true);
  24063. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24064. // Restore effect Layer stencil
  24065. if (needStencil) {
  24066. this._engine.setStencilBuffer(stencilState);
  24067. }
  24068. // Bounding boxes
  24069. if (this._boundingBoxRenderer) {
  24070. this._boundingBoxRenderer.render();
  24071. }
  24072. // Lens flares
  24073. if (this.lensFlaresEnabled) {
  24074. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24075. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24076. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24077. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24078. lensFlareSystem.render();
  24079. }
  24080. }
  24081. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24082. }
  24083. // Foregrounds
  24084. if (this.layers.length) {
  24085. engine.setDepthBuffer(false);
  24086. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24087. layer = this.layers[layerIndex];
  24088. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24089. layer.render();
  24090. }
  24091. }
  24092. engine.setDepthBuffer(true);
  24093. }
  24094. // Effect Layer
  24095. if (renderEffects) {
  24096. engine.setDepthBuffer(false);
  24097. for (var i = 0; i < this.effectLayers.length; i++) {
  24098. if (this.effectLayers[i].shouldRender()) {
  24099. this.effectLayers[i].render();
  24100. }
  24101. }
  24102. engine.setDepthBuffer(true);
  24103. }
  24104. // Finalize frame
  24105. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24106. // Reset some special arrays
  24107. this._renderTargets.reset();
  24108. this._alternateRendering = false;
  24109. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24110. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24111. };
  24112. Scene.prototype._processSubCameras = function (camera) {
  24113. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24114. this._renderForCamera(camera);
  24115. return;
  24116. }
  24117. // rig cameras
  24118. for (var index = 0; index < camera._rigCameras.length; index++) {
  24119. this._renderForCamera(camera._rigCameras[index], camera);
  24120. }
  24121. this.activeCamera = camera;
  24122. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24123. };
  24124. Scene.prototype._checkIntersections = function () {
  24125. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24126. var sourceMesh = this._meshesForIntersections.data[index];
  24127. if (!sourceMesh.actionManager) {
  24128. continue;
  24129. }
  24130. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24131. var action = sourceMesh.actionManager.actions[actionIndex];
  24132. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24133. var parameters = action.getTriggerParameter();
  24134. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24135. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24136. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24137. if (areIntersecting && currentIntersectionInProgress === -1) {
  24138. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24139. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24140. sourceMesh._intersectionsInProgress.push(otherMesh);
  24141. }
  24142. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24143. sourceMesh._intersectionsInProgress.push(otherMesh);
  24144. }
  24145. }
  24146. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24147. //They intersected, and now they don't.
  24148. //is this trigger an exit trigger? execute an event.
  24149. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24150. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24151. }
  24152. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24153. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24154. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24155. }
  24156. }
  24157. }
  24158. }
  24159. }
  24160. };
  24161. Scene.prototype.render = function () {
  24162. if (this.isDisposed) {
  24163. return;
  24164. }
  24165. this._activeParticles.fetchNewFrame();
  24166. this._totalVertices.fetchNewFrame();
  24167. this._activeIndices.fetchNewFrame();
  24168. this._activeBones.fetchNewFrame();
  24169. this._meshesForIntersections.reset();
  24170. this.resetCachedMaterial();
  24171. this.onBeforeAnimationsObservable.notifyObservers(this);
  24172. // Actions
  24173. if (this.actionManager) {
  24174. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24175. }
  24176. //Simplification Queue
  24177. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24178. this.simplificationQueue.executeNext();
  24179. }
  24180. if (this._engine.isDeterministicLockStep()) {
  24181. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24182. var defaultFPS = (60.0 / 1000.0);
  24183. var defaultFrameTime = 1000 / 60; // frame time in MS
  24184. if (this._physicsEngine) {
  24185. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24186. }
  24187. var stepsTaken = 0;
  24188. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24189. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24190. internalSteps = Math.min(internalSteps, maxSubSteps);
  24191. do {
  24192. this.onBeforeStepObservable.notifyObservers(this);
  24193. // Animations
  24194. this._animationRatio = defaultFrameTime * defaultFPS;
  24195. this._animate();
  24196. this.onAfterAnimationsObservable.notifyObservers(this);
  24197. // Physics
  24198. if (this._physicsEngine) {
  24199. this.onBeforePhysicsObservable.notifyObservers(this);
  24200. this._physicsEngine._step(defaultFrameTime / 1000);
  24201. this.onAfterPhysicsObservable.notifyObservers(this);
  24202. }
  24203. this.onAfterStepObservable.notifyObservers(this);
  24204. this._currentStepId++;
  24205. stepsTaken++;
  24206. deltaTime -= defaultFrameTime;
  24207. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24208. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24209. }
  24210. else {
  24211. // Animations
  24212. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24213. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24214. this._animate();
  24215. this.onAfterAnimationsObservable.notifyObservers(this);
  24216. // Physics
  24217. if (this._physicsEngine) {
  24218. this.onBeforePhysicsObservable.notifyObservers(this);
  24219. this._physicsEngine._step(deltaTime / 1000.0);
  24220. this.onAfterPhysicsObservable.notifyObservers(this);
  24221. }
  24222. }
  24223. // update gamepad manager
  24224. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24225. this._gamepadManager._checkGamepadsStatus();
  24226. }
  24227. // Before render
  24228. this.onBeforeRenderObservable.notifyObservers(this);
  24229. // Update Cameras
  24230. if (this.activeCameras.length > 0) {
  24231. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24232. var camera = this.activeCameras[cameraIndex];
  24233. camera.update();
  24234. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24235. // rig cameras
  24236. for (var index = 0; index < camera._rigCameras.length; index++) {
  24237. camera._rigCameras[index].update();
  24238. }
  24239. }
  24240. }
  24241. }
  24242. else if (this.activeCamera) {
  24243. this.activeCamera.update();
  24244. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24245. // rig cameras
  24246. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24247. this.activeCamera._rigCameras[index].update();
  24248. }
  24249. }
  24250. }
  24251. // Customs render targets
  24252. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24253. var engine = this.getEngine();
  24254. var currentActiveCamera = this.activeCamera;
  24255. if (this.renderTargetsEnabled) {
  24256. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24257. this._intermediateRendering = true;
  24258. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24259. var renderTarget = this.customRenderTargets[customIndex];
  24260. if (renderTarget._shouldRender()) {
  24261. this._renderId++;
  24262. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24263. if (!this.activeCamera)
  24264. throw new Error("Active camera not set");
  24265. // Viewport
  24266. engine.setViewport(this.activeCamera.viewport);
  24267. // Camera
  24268. this.updateTransformMatrix();
  24269. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24270. }
  24271. }
  24272. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24273. this._intermediateRendering = false;
  24274. this._renderId++;
  24275. }
  24276. // Restore back buffer
  24277. if (this.customRenderTargets.length > 0) {
  24278. engine.restoreDefaultFramebuffer();
  24279. }
  24280. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24281. this.activeCamera = currentActiveCamera;
  24282. // Procedural textures
  24283. if (this.proceduralTexturesEnabled) {
  24284. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24285. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24286. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24287. if (proceduralTexture._shouldRender()) {
  24288. proceduralTexture.render();
  24289. }
  24290. }
  24291. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24292. }
  24293. // Clear
  24294. if (this.autoClearDepthAndStencil || this.autoClear) {
  24295. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24296. }
  24297. // Shadows
  24298. if (this.shadowsEnabled) {
  24299. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24300. var light = this.lights[lightIndex];
  24301. var shadowGenerator = light.getShadowGenerator();
  24302. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24303. var shadowMap = (shadowGenerator.getShadowMap());
  24304. if (this.textures.indexOf(shadowMap) !== -1) {
  24305. this._renderTargets.push(shadowMap);
  24306. }
  24307. }
  24308. }
  24309. }
  24310. // Depth renderer
  24311. for (var key in this._depthRenderer) {
  24312. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24313. }
  24314. // Geometry renderer
  24315. if (this._geometryBufferRenderer) {
  24316. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24317. }
  24318. // RenderPipeline
  24319. if (this._postProcessRenderPipelineManager) {
  24320. this._postProcessRenderPipelineManager.update();
  24321. }
  24322. // Multi-cameras?
  24323. if (this.activeCameras.length > 0) {
  24324. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24325. if (cameraIndex > 0) {
  24326. this._engine.clear(null, false, true, true);
  24327. }
  24328. this._processSubCameras(this.activeCameras[cameraIndex]);
  24329. }
  24330. }
  24331. else {
  24332. if (!this.activeCamera) {
  24333. throw new Error("No camera defined");
  24334. }
  24335. this._processSubCameras(this.activeCamera);
  24336. }
  24337. // Intersection checks
  24338. this._checkIntersections();
  24339. // Update the audio listener attached to the camera
  24340. if (BABYLON.AudioEngine) {
  24341. this._updateAudioParameters();
  24342. }
  24343. // After render
  24344. if (this.afterRender) {
  24345. this.afterRender();
  24346. }
  24347. this.onAfterRenderObservable.notifyObservers(this);
  24348. // Cleaning
  24349. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24350. var data = this._toBeDisposed.data[index];
  24351. if (data) {
  24352. data.dispose();
  24353. }
  24354. this._toBeDisposed[index] = null;
  24355. }
  24356. this._toBeDisposed.reset();
  24357. if (this.dumpNextRenderTargets) {
  24358. this.dumpNextRenderTargets = false;
  24359. }
  24360. this._activeBones.addCount(0, true);
  24361. this._activeIndices.addCount(0, true);
  24362. this._activeParticles.addCount(0, true);
  24363. };
  24364. Scene.prototype._updateAudioParameters = function () {
  24365. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24366. return;
  24367. }
  24368. var listeningCamera;
  24369. var audioEngine = BABYLON.Engine.audioEngine;
  24370. if (this.activeCameras.length > 0) {
  24371. listeningCamera = this.activeCameras[0];
  24372. }
  24373. else {
  24374. listeningCamera = this.activeCamera;
  24375. }
  24376. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24377. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24378. // for VR cameras
  24379. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24380. listeningCamera = listeningCamera.rigCameras[0];
  24381. }
  24382. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24383. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24384. cameraDirection.normalize();
  24385. // To avoid some errors on GearVR
  24386. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24387. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24388. }
  24389. var i;
  24390. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24391. var sound = this.mainSoundTrack.soundCollection[i];
  24392. if (sound.useCustomAttenuation) {
  24393. sound.updateDistanceFromListener();
  24394. }
  24395. }
  24396. for (i = 0; i < this.soundTracks.length; i++) {
  24397. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24398. sound = this.soundTracks[i].soundCollection[j];
  24399. if (sound.useCustomAttenuation) {
  24400. sound.updateDistanceFromListener();
  24401. }
  24402. }
  24403. }
  24404. }
  24405. };
  24406. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24407. // Audio
  24408. get: function () {
  24409. return this._audioEnabled;
  24410. },
  24411. set: function (value) {
  24412. this._audioEnabled = value;
  24413. if (BABYLON.AudioEngine) {
  24414. if (this._audioEnabled) {
  24415. this._enableAudio();
  24416. }
  24417. else {
  24418. this._disableAudio();
  24419. }
  24420. }
  24421. },
  24422. enumerable: true,
  24423. configurable: true
  24424. });
  24425. Scene.prototype._disableAudio = function () {
  24426. var i;
  24427. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24428. this.mainSoundTrack.soundCollection[i].pause();
  24429. }
  24430. for (i = 0; i < this.soundTracks.length; i++) {
  24431. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24432. this.soundTracks[i].soundCollection[j].pause();
  24433. }
  24434. }
  24435. };
  24436. Scene.prototype._enableAudio = function () {
  24437. var i;
  24438. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24439. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  24440. this.mainSoundTrack.soundCollection[i].play();
  24441. }
  24442. }
  24443. for (i = 0; i < this.soundTracks.length; i++) {
  24444. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24445. if (this.soundTracks[i].soundCollection[j].isPaused) {
  24446. this.soundTracks[i].soundCollection[j].play();
  24447. }
  24448. }
  24449. }
  24450. };
  24451. Object.defineProperty(Scene.prototype, "headphone", {
  24452. get: function () {
  24453. return this._headphone;
  24454. },
  24455. set: function (value) {
  24456. this._headphone = value;
  24457. if (BABYLON.AudioEngine) {
  24458. if (this._headphone) {
  24459. this._switchAudioModeForHeadphones();
  24460. }
  24461. else {
  24462. this._switchAudioModeForNormalSpeakers();
  24463. }
  24464. }
  24465. },
  24466. enumerable: true,
  24467. configurable: true
  24468. });
  24469. Scene.prototype._switchAudioModeForHeadphones = function () {
  24470. this.mainSoundTrack.switchPanningModelToHRTF();
  24471. for (var i = 0; i < this.soundTracks.length; i++) {
  24472. this.soundTracks[i].switchPanningModelToHRTF();
  24473. }
  24474. };
  24475. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  24476. this.mainSoundTrack.switchPanningModelToEqualPower();
  24477. for (var i = 0; i < this.soundTracks.length; i++) {
  24478. this.soundTracks[i].switchPanningModelToEqualPower();
  24479. }
  24480. };
  24481. /**
  24482. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  24483. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  24484. * @returns the created depth renderer
  24485. */
  24486. Scene.prototype.enableDepthRenderer = function (camera) {
  24487. camera = camera || this.activeCamera;
  24488. if (!camera) {
  24489. throw "No camera available to enable depth renderer";
  24490. }
  24491. if (!this._depthRenderer[camera.id]) {
  24492. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, BABYLON.Engine.TEXTURETYPE_FLOAT, camera);
  24493. }
  24494. return this._depthRenderer[camera.id];
  24495. };
  24496. /**
  24497. * Disables a depth renderer for a given camera
  24498. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  24499. */
  24500. Scene.prototype.disableDepthRenderer = function (camera) {
  24501. camera = camera || this.activeCamera;
  24502. if (!camera || !this._depthRenderer[camera.id]) {
  24503. return;
  24504. }
  24505. this._depthRenderer[camera.id].dispose();
  24506. delete this._depthRenderer[camera.id];
  24507. };
  24508. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  24509. if (ratio === void 0) { ratio = 1; }
  24510. if (this._geometryBufferRenderer) {
  24511. return this._geometryBufferRenderer;
  24512. }
  24513. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  24514. if (!this._geometryBufferRenderer.isSupported) {
  24515. this._geometryBufferRenderer = null;
  24516. }
  24517. return this._geometryBufferRenderer;
  24518. };
  24519. Scene.prototype.disableGeometryBufferRenderer = function () {
  24520. if (!this._geometryBufferRenderer) {
  24521. return;
  24522. }
  24523. this._geometryBufferRenderer.dispose();
  24524. this._geometryBufferRenderer = null;
  24525. };
  24526. Scene.prototype.freezeMaterials = function () {
  24527. for (var i = 0; i < this.materials.length; i++) {
  24528. this.materials[i].freeze();
  24529. }
  24530. };
  24531. Scene.prototype.unfreezeMaterials = function () {
  24532. for (var i = 0; i < this.materials.length; i++) {
  24533. this.materials[i].unfreeze();
  24534. }
  24535. };
  24536. Scene.prototype.dispose = function () {
  24537. this.beforeRender = null;
  24538. this.afterRender = null;
  24539. this.skeletons = [];
  24540. this.morphTargetManagers = [];
  24541. this.importedMeshesFiles = new Array();
  24542. this.stopAllAnimations();
  24543. this.resetCachedMaterial();
  24544. for (var key in this._depthRenderer) {
  24545. this._depthRenderer[key].dispose();
  24546. }
  24547. if (this._gamepadManager) {
  24548. this._gamepadManager.dispose();
  24549. this._gamepadManager = null;
  24550. }
  24551. // Smart arrays
  24552. if (this.activeCamera) {
  24553. this.activeCamera._activeMeshes.dispose();
  24554. this.activeCamera = null;
  24555. }
  24556. this._activeMeshes.dispose();
  24557. this._renderingManager.dispose();
  24558. this._processedMaterials.dispose();
  24559. this._activeParticleSystems.dispose();
  24560. this._activeSkeletons.dispose();
  24561. this._softwareSkinnedMeshes.dispose();
  24562. this._renderTargets.dispose();
  24563. if (this._boundingBoxRenderer) {
  24564. this._boundingBoxRenderer.dispose();
  24565. }
  24566. this._meshesForIntersections.dispose();
  24567. this._toBeDisposed.dispose();
  24568. // Abort active requests
  24569. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  24570. var request = _a[_i];
  24571. request.abort();
  24572. }
  24573. // Debug layer
  24574. if (this._debugLayer) {
  24575. this._debugLayer.hide();
  24576. }
  24577. // Events
  24578. this.onDisposeObservable.notifyObservers(this);
  24579. this.onDisposeObservable.clear();
  24580. this.onBeforeRenderObservable.clear();
  24581. this.onAfterRenderObservable.clear();
  24582. this.OnBeforeRenderTargetsRenderObservable.clear();
  24583. this.OnAfterRenderTargetsRenderObservable.clear();
  24584. this.onAfterStepObservable.clear();
  24585. this.onBeforeStepObservable.clear();
  24586. this.onBeforeActiveMeshesEvaluationObservable.clear();
  24587. this.onAfterActiveMeshesEvaluationObservable.clear();
  24588. this.onBeforeParticlesRenderingObservable.clear();
  24589. this.onAfterParticlesRenderingObservable.clear();
  24590. this.onBeforeSpritesRenderingObservable.clear();
  24591. this.onAfterSpritesRenderingObservable.clear();
  24592. this.onBeforeDrawPhaseObservable.clear();
  24593. this.onAfterDrawPhaseObservable.clear();
  24594. this.onBeforePhysicsObservable.clear();
  24595. this.onAfterPhysicsObservable.clear();
  24596. this.onBeforeAnimationsObservable.clear();
  24597. this.onAfterAnimationsObservable.clear();
  24598. this.onDataLoadedObservable.clear();
  24599. this.detachControl();
  24600. // Release sounds & sounds tracks
  24601. if (BABYLON.AudioEngine) {
  24602. this.disposeSounds();
  24603. }
  24604. // VR Helper
  24605. if (this.VRHelper) {
  24606. this.VRHelper.dispose();
  24607. }
  24608. // Detach cameras
  24609. var canvas = this._engine.getRenderingCanvas();
  24610. if (canvas) {
  24611. var index;
  24612. for (index = 0; index < this.cameras.length; index++) {
  24613. this.cameras[index].detachControl(canvas);
  24614. }
  24615. }
  24616. // Release animation groups
  24617. while (this.animationGroups.length) {
  24618. this.animationGroups[0].dispose();
  24619. }
  24620. // Release lights
  24621. while (this.lights.length) {
  24622. this.lights[0].dispose();
  24623. }
  24624. // Release meshes
  24625. while (this.meshes.length) {
  24626. this.meshes[0].dispose(true);
  24627. }
  24628. while (this.transformNodes.length) {
  24629. this.removeTransformNode(this.transformNodes[0]);
  24630. }
  24631. // Release cameras
  24632. while (this.cameras.length) {
  24633. this.cameras[0].dispose();
  24634. }
  24635. // Release materials
  24636. if (this.defaultMaterial) {
  24637. this.defaultMaterial.dispose();
  24638. }
  24639. while (this.multiMaterials.length) {
  24640. this.multiMaterials[0].dispose();
  24641. }
  24642. while (this.materials.length) {
  24643. this.materials[0].dispose();
  24644. }
  24645. // Release particles
  24646. while (this.particleSystems.length) {
  24647. this.particleSystems[0].dispose();
  24648. }
  24649. // Release sprites
  24650. while (this.spriteManagers.length) {
  24651. this.spriteManagers[0].dispose();
  24652. }
  24653. // Release postProcesses
  24654. while (this.postProcesses.length) {
  24655. this.postProcesses[0].dispose();
  24656. }
  24657. // Release layers
  24658. while (this.layers.length) {
  24659. this.layers[0].dispose();
  24660. }
  24661. while (this.effectLayers.length) {
  24662. this.effectLayers[0].dispose();
  24663. }
  24664. // Release textures
  24665. while (this.textures.length) {
  24666. this.textures[0].dispose();
  24667. }
  24668. // Release UBO
  24669. this._sceneUbo.dispose();
  24670. if (this._alternateSceneUbo) {
  24671. this._alternateSceneUbo.dispose();
  24672. }
  24673. // Post-processes
  24674. this.postProcessManager.dispose();
  24675. if (this._postProcessRenderPipelineManager) {
  24676. this._postProcessRenderPipelineManager.dispose();
  24677. }
  24678. // Physics
  24679. if (this._physicsEngine) {
  24680. this.disablePhysicsEngine();
  24681. }
  24682. // Remove from engine
  24683. index = this._engine.scenes.indexOf(this);
  24684. if (index > -1) {
  24685. this._engine.scenes.splice(index, 1);
  24686. }
  24687. this._engine.wipeCaches(true);
  24688. this._isDisposed = true;
  24689. };
  24690. Object.defineProperty(Scene.prototype, "isDisposed", {
  24691. get: function () {
  24692. return this._isDisposed;
  24693. },
  24694. enumerable: true,
  24695. configurable: true
  24696. });
  24697. // Release sounds & sounds tracks
  24698. Scene.prototype.disposeSounds = function () {
  24699. if (!this._mainSoundTrack) {
  24700. return;
  24701. }
  24702. this.mainSoundTrack.dispose();
  24703. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  24704. this.soundTracks[scIndex].dispose();
  24705. }
  24706. };
  24707. // Octrees
  24708. /**
  24709. * Get the world extend vectors with an optional filter
  24710. *
  24711. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  24712. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  24713. */
  24714. Scene.prototype.getWorldExtends = function (filterPredicate) {
  24715. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  24716. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  24717. filterPredicate = filterPredicate || (function () { return true; });
  24718. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  24719. mesh.computeWorldMatrix(true);
  24720. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  24721. return;
  24722. }
  24723. var boundingInfo = mesh.getBoundingInfo();
  24724. var minBox = boundingInfo.boundingBox.minimumWorld;
  24725. var maxBox = boundingInfo.boundingBox.maximumWorld;
  24726. BABYLON.Tools.CheckExtends(minBox, min, max);
  24727. BABYLON.Tools.CheckExtends(maxBox, min, max);
  24728. });
  24729. return {
  24730. min: min,
  24731. max: max
  24732. };
  24733. };
  24734. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  24735. if (maxCapacity === void 0) { maxCapacity = 64; }
  24736. if (maxDepth === void 0) { maxDepth = 2; }
  24737. if (!this._selectionOctree) {
  24738. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  24739. }
  24740. var worldExtends = this.getWorldExtends();
  24741. // Update octree
  24742. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  24743. return this._selectionOctree;
  24744. };
  24745. // Picking
  24746. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  24747. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24748. var result = BABYLON.Ray.Zero();
  24749. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  24750. return result;
  24751. };
  24752. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  24753. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24754. var engine = this._engine;
  24755. if (!camera) {
  24756. if (!this.activeCamera)
  24757. throw new Error("Active camera not set");
  24758. camera = this.activeCamera;
  24759. }
  24760. var cameraViewport = camera.viewport;
  24761. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24762. // Moving coordinates to local viewport world
  24763. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24764. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24765. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  24766. return this;
  24767. };
  24768. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  24769. var result = BABYLON.Ray.Zero();
  24770. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  24771. return result;
  24772. };
  24773. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  24774. if (!BABYLON.PickingInfo) {
  24775. return this;
  24776. }
  24777. var engine = this._engine;
  24778. if (!camera) {
  24779. if (!this.activeCamera)
  24780. throw new Error("Active camera not set");
  24781. camera = this.activeCamera;
  24782. }
  24783. var cameraViewport = camera.viewport;
  24784. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24785. var identity = BABYLON.Matrix.Identity();
  24786. // Moving coordinates to local viewport world
  24787. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24788. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24789. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  24790. return this;
  24791. };
  24792. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  24793. if (!BABYLON.PickingInfo) {
  24794. return null;
  24795. }
  24796. var pickingInfo = null;
  24797. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24798. var mesh = this.meshes[meshIndex];
  24799. if (predicate) {
  24800. if (!predicate(mesh)) {
  24801. continue;
  24802. }
  24803. }
  24804. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24805. continue;
  24806. }
  24807. var world = mesh.getWorldMatrix();
  24808. var ray = rayFunction(world);
  24809. var result = mesh.intersects(ray, fastCheck);
  24810. if (!result || !result.hit)
  24811. continue;
  24812. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24813. continue;
  24814. pickingInfo = result;
  24815. if (fastCheck) {
  24816. break;
  24817. }
  24818. }
  24819. return pickingInfo || new BABYLON.PickingInfo();
  24820. };
  24821. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  24822. if (!BABYLON.PickingInfo) {
  24823. return null;
  24824. }
  24825. var pickingInfos = new Array();
  24826. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24827. var mesh = this.meshes[meshIndex];
  24828. if (predicate) {
  24829. if (!predicate(mesh)) {
  24830. continue;
  24831. }
  24832. }
  24833. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24834. continue;
  24835. }
  24836. var world = mesh.getWorldMatrix();
  24837. var ray = rayFunction(world);
  24838. var result = mesh.intersects(ray, false);
  24839. if (!result || !result.hit)
  24840. continue;
  24841. pickingInfos.push(result);
  24842. }
  24843. return pickingInfos;
  24844. };
  24845. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  24846. if (!BABYLON.PickingInfo) {
  24847. return null;
  24848. }
  24849. var pickingInfo = null;
  24850. if (!camera) {
  24851. if (!this.activeCamera) {
  24852. return null;
  24853. }
  24854. camera = this.activeCamera;
  24855. }
  24856. if (this.spriteManagers.length > 0) {
  24857. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  24858. var spriteManager = this.spriteManagers[spriteIndex];
  24859. if (!spriteManager.isPickable) {
  24860. continue;
  24861. }
  24862. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  24863. if (!result || !result.hit)
  24864. continue;
  24865. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24866. continue;
  24867. pickingInfo = result;
  24868. if (fastCheck) {
  24869. break;
  24870. }
  24871. }
  24872. }
  24873. return pickingInfo || new BABYLON.PickingInfo();
  24874. };
  24875. /** Launch a ray to try to pick a mesh in the scene
  24876. * @param x position on screen
  24877. * @param y position on screen
  24878. * @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
  24879. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24880. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24881. */
  24882. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  24883. var _this = this;
  24884. if (!BABYLON.PickingInfo) {
  24885. return null;
  24886. }
  24887. return this._internalPick(function (world) {
  24888. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  24889. return _this._tempPickingRay;
  24890. }, predicate, fastCheck);
  24891. };
  24892. /** Launch a ray to try to pick a sprite in the scene
  24893. * @param x position on screen
  24894. * @param y position on screen
  24895. * @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
  24896. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24897. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24898. */
  24899. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  24900. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  24901. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  24902. };
  24903. /** Use the given ray to pick a mesh in the scene
  24904. * @param ray The ray to use to pick meshes
  24905. * @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
  24906. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24907. */
  24908. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  24909. var _this = this;
  24910. return this._internalPick(function (world) {
  24911. if (!_this._pickWithRayInverseMatrix) {
  24912. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24913. }
  24914. world.invertToRef(_this._pickWithRayInverseMatrix);
  24915. if (!_this._cachedRayForTransform) {
  24916. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24917. }
  24918. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24919. return _this._cachedRayForTransform;
  24920. }, predicate, fastCheck);
  24921. };
  24922. /**
  24923. * Launch a ray to try to pick a mesh in the scene
  24924. * @param x X position on screen
  24925. * @param y Y position on screen
  24926. * @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
  24927. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24928. */
  24929. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  24930. var _this = this;
  24931. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  24932. };
  24933. /**
  24934. * Launch a ray to try to pick a mesh in the scene
  24935. * @param ray Ray to use
  24936. * @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
  24937. */
  24938. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  24939. var _this = this;
  24940. return this._internalMultiPick(function (world) {
  24941. if (!_this._pickWithRayInverseMatrix) {
  24942. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24943. }
  24944. world.invertToRef(_this._pickWithRayInverseMatrix);
  24945. if (!_this._cachedRayForTransform) {
  24946. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24947. }
  24948. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24949. return _this._cachedRayForTransform;
  24950. }, predicate);
  24951. };
  24952. Scene.prototype.setPointerOverMesh = function (mesh) {
  24953. if (this._pointerOverMesh === mesh) {
  24954. return;
  24955. }
  24956. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24957. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24958. }
  24959. this._pointerOverMesh = mesh;
  24960. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24961. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24962. }
  24963. };
  24964. Scene.prototype.getPointerOverMesh = function () {
  24965. return this._pointerOverMesh;
  24966. };
  24967. Scene.prototype.setPointerOverSprite = function (sprite) {
  24968. if (this._pointerOverSprite === sprite) {
  24969. return;
  24970. }
  24971. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24972. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24973. }
  24974. this._pointerOverSprite = sprite;
  24975. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24976. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24977. }
  24978. };
  24979. Scene.prototype.getPointerOverSprite = function () {
  24980. return this._pointerOverSprite;
  24981. };
  24982. // Physics
  24983. Scene.prototype.getPhysicsEngine = function () {
  24984. return this._physicsEngine;
  24985. };
  24986. /**
  24987. * Enables physics to the current scene
  24988. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  24989. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  24990. * @return {boolean} was the physics engine initialized
  24991. */
  24992. Scene.prototype.enablePhysics = function (gravity, plugin) {
  24993. if (gravity === void 0) { gravity = null; }
  24994. if (this._physicsEngine) {
  24995. return true;
  24996. }
  24997. try {
  24998. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  24999. return true;
  25000. }
  25001. catch (e) {
  25002. BABYLON.Tools.Error(e.message);
  25003. return false;
  25004. }
  25005. };
  25006. Scene.prototype.disablePhysicsEngine = function () {
  25007. if (!this._physicsEngine) {
  25008. return;
  25009. }
  25010. this._physicsEngine.dispose();
  25011. this._physicsEngine = null;
  25012. };
  25013. Scene.prototype.isPhysicsEnabled = function () {
  25014. return this._physicsEngine !== undefined;
  25015. };
  25016. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25017. var mesh = compound.parts[0].mesh;
  25018. if (mesh.physicsImpostor) {
  25019. mesh.physicsImpostor.dispose();
  25020. mesh.physicsImpostor = null;
  25021. }
  25022. };
  25023. // Misc.
  25024. Scene.prototype._rebuildGeometries = function () {
  25025. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25026. var geometry = _a[_i];
  25027. geometry._rebuild();
  25028. }
  25029. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25030. var mesh = _c[_b];
  25031. mesh._rebuild();
  25032. }
  25033. if (this.postProcessManager) {
  25034. this.postProcessManager._rebuild();
  25035. }
  25036. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25037. var layer = _e[_d];
  25038. layer._rebuild();
  25039. }
  25040. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25041. var effectLayer = _g[_f];
  25042. effectLayer._rebuild();
  25043. }
  25044. if (this._boundingBoxRenderer) {
  25045. this._boundingBoxRenderer._rebuild();
  25046. }
  25047. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25048. var system = _j[_h];
  25049. system.rebuild();
  25050. }
  25051. if (this._postProcessRenderPipelineManager) {
  25052. this._postProcessRenderPipelineManager._rebuild();
  25053. }
  25054. };
  25055. Scene.prototype._rebuildTextures = function () {
  25056. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25057. var texture = _a[_i];
  25058. texture._rebuild();
  25059. }
  25060. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25061. };
  25062. /**
  25063. * Creates a default light for the scene.
  25064. * @param replace Whether to replace the existing lights in the scene.
  25065. */
  25066. Scene.prototype.createDefaultLight = function (replace) {
  25067. if (replace === void 0) { replace = false; }
  25068. // Dispose existing light in replace mode.
  25069. if (replace) {
  25070. if (this.lights) {
  25071. for (var i = 0; i < this.lights.length; i++) {
  25072. this.lights[i].dispose();
  25073. }
  25074. }
  25075. }
  25076. // Light
  25077. if (this.lights.length === 0) {
  25078. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25079. }
  25080. };
  25081. /**
  25082. * Creates a default camera for the scene.
  25083. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25084. * @param replace Whether to replace the existing active camera in the scene.
  25085. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25086. */
  25087. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25088. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25089. if (replace === void 0) { replace = false; }
  25090. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25091. // Dispose existing camera in replace mode.
  25092. if (replace) {
  25093. if (this.activeCamera) {
  25094. this.activeCamera.dispose();
  25095. this.activeCamera = null;
  25096. }
  25097. }
  25098. // Camera
  25099. if (!this.activeCamera) {
  25100. var worldExtends = this.getWorldExtends();
  25101. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25102. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25103. var camera;
  25104. var radius = worldSize.length() * 1.5;
  25105. // empty scene scenario!
  25106. if (!isFinite(radius)) {
  25107. radius = 1;
  25108. worldCenter.copyFromFloats(0, 0, 0);
  25109. }
  25110. if (createArcRotateCamera) {
  25111. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25112. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25113. arcRotateCamera.wheelPrecision = 100 / radius;
  25114. camera = arcRotateCamera;
  25115. }
  25116. else {
  25117. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25118. freeCamera.setTarget(worldCenter);
  25119. camera = freeCamera;
  25120. }
  25121. camera.minZ = radius * 0.01;
  25122. camera.maxZ = radius * 1000;
  25123. camera.speed = radius * 0.2;
  25124. this.activeCamera = camera;
  25125. var canvas = this.getEngine().getRenderingCanvas();
  25126. if (attachCameraControls && canvas) {
  25127. camera.attachControl(canvas);
  25128. }
  25129. }
  25130. };
  25131. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25132. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25133. if (replace === void 0) { replace = false; }
  25134. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25135. this.createDefaultLight(replace);
  25136. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25137. };
  25138. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25139. if (pbr === void 0) { pbr = false; }
  25140. if (scale === void 0) { scale = 1000; }
  25141. if (blur === void 0) { blur = 0; }
  25142. if (environmentTexture) {
  25143. this.environmentTexture = environmentTexture;
  25144. }
  25145. if (!this.environmentTexture) {
  25146. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25147. return null;
  25148. }
  25149. // Skybox
  25150. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25151. if (pbr) {
  25152. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25153. hdrSkyboxMaterial.backFaceCulling = false;
  25154. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25155. if (hdrSkyboxMaterial.reflectionTexture) {
  25156. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25157. }
  25158. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25159. hdrSkyboxMaterial.disableLighting = true;
  25160. hdrSkyboxMaterial.twoSidedLighting = true;
  25161. hdrSkybox.infiniteDistance = true;
  25162. hdrSkybox.material = hdrSkyboxMaterial;
  25163. }
  25164. else {
  25165. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25166. skyboxMaterial.backFaceCulling = false;
  25167. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25168. if (skyboxMaterial.reflectionTexture) {
  25169. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25170. }
  25171. skyboxMaterial.disableLighting = true;
  25172. hdrSkybox.infiniteDistance = true;
  25173. hdrSkybox.material = skyboxMaterial;
  25174. }
  25175. return hdrSkybox;
  25176. };
  25177. Scene.prototype.createDefaultEnvironment = function (options) {
  25178. if (BABYLON.EnvironmentHelper) {
  25179. return new BABYLON.EnvironmentHelper(options, this);
  25180. }
  25181. return null;
  25182. };
  25183. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25184. if (webVROptions === void 0) { webVROptions = {}; }
  25185. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25186. };
  25187. // Tags
  25188. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25189. if (tagsQuery === undefined) {
  25190. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25191. return list;
  25192. }
  25193. var listByTags = [];
  25194. forEach = forEach || (function (item) { return; });
  25195. for (var i in list) {
  25196. var item = list[i];
  25197. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25198. listByTags.push(item);
  25199. forEach(item);
  25200. }
  25201. }
  25202. return listByTags;
  25203. };
  25204. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25205. return this._getByTags(this.meshes, tagsQuery, forEach);
  25206. };
  25207. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25208. return this._getByTags(this.cameras, tagsQuery, forEach);
  25209. };
  25210. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25211. return this._getByTags(this.lights, tagsQuery, forEach);
  25212. };
  25213. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25214. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25215. };
  25216. /**
  25217. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25218. * This allowed control for front to back rendering or reversly depending of the special needs.
  25219. *
  25220. * @param renderingGroupId The rendering group id corresponding to its index
  25221. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25222. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25223. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25224. */
  25225. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25226. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25227. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25228. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25229. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25230. };
  25231. /**
  25232. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25233. *
  25234. * @param renderingGroupId The rendering group id corresponding to its index
  25235. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25236. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25237. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25238. */
  25239. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25240. if (depth === void 0) { depth = true; }
  25241. if (stencil === void 0) { stencil = true; }
  25242. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25243. };
  25244. /**
  25245. * Will flag all materials as dirty to trigger new shader compilation
  25246. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25247. */
  25248. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25249. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25250. var material = _a[_i];
  25251. if (predicate && !predicate(material)) {
  25252. continue;
  25253. }
  25254. material.markAsDirty(flag);
  25255. }
  25256. };
  25257. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25258. var _this = this;
  25259. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25260. this._activeRequests.push(request);
  25261. request.onCompleteObservable.add(function (request) {
  25262. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25263. });
  25264. return request;
  25265. };
  25266. /** @ignore */
  25267. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25268. var _this = this;
  25269. return new Promise(function (resolve, reject) {
  25270. _this._loadFile(url, function (data) {
  25271. resolve(data);
  25272. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25273. reject(exception);
  25274. });
  25275. });
  25276. };
  25277. // Statics
  25278. Scene._FOGMODE_NONE = 0;
  25279. Scene._FOGMODE_EXP = 1;
  25280. Scene._FOGMODE_EXP2 = 2;
  25281. Scene._FOGMODE_LINEAR = 3;
  25282. Scene._uniqueIdCounter = 0;
  25283. Scene.MinDeltaTime = 1.0;
  25284. Scene.MaxDeltaTime = 1000.0;
  25285. /** The distance in pixel that you have to move to prevent some events */
  25286. Scene.DragMovementThreshold = 10; // in pixels
  25287. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25288. Scene.LongPressDelay = 500; // in milliseconds
  25289. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25290. Scene.DoubleClickDelay = 300; // in milliseconds
  25291. /** If you need to check double click without raising a single click at first click, enable this flag */
  25292. Scene.ExclusiveDoubleClickMode = false;
  25293. return Scene;
  25294. }());
  25295. BABYLON.Scene = Scene;
  25296. })(BABYLON || (BABYLON = {}));
  25297. //# sourceMappingURL=babylon.scene.js.map
  25298. var BABYLON;
  25299. (function (BABYLON) {
  25300. /**
  25301. * Set of assets to keep when moving a scene into an asset container.
  25302. */
  25303. var KeepAssets = /** @class */ (function () {
  25304. function KeepAssets() {
  25305. /**
  25306. * Cameras to keep.
  25307. */
  25308. this.cameras = new Array();
  25309. /**
  25310. * Lights to keep.
  25311. */
  25312. this.lights = new Array();
  25313. /**
  25314. * Meshes to keep.
  25315. */
  25316. this.meshes = new Array();
  25317. /**
  25318. * Skeletons to keep.
  25319. */
  25320. this.skeletons = new Array();
  25321. /**
  25322. * ParticleSystems to keep.
  25323. */
  25324. this.particleSystems = new Array();
  25325. /**
  25326. * Animations to keep.
  25327. */
  25328. this.animations = new Array();
  25329. /**
  25330. * MultiMaterials to keep.
  25331. */
  25332. this.multiMaterials = new Array();
  25333. /**
  25334. * Materials to keep.
  25335. */
  25336. this.materials = new Array();
  25337. /**
  25338. * MorphTargetManagers to keep.
  25339. */
  25340. this.morphTargetManagers = new Array();
  25341. /**
  25342. * Geometries to keep.
  25343. */
  25344. this.geometries = new Array();
  25345. /**
  25346. * TransformNodes to keep.
  25347. */
  25348. this.transformNodes = new Array();
  25349. /**
  25350. * LensFlareSystems to keep.
  25351. */
  25352. this.lensFlareSystems = new Array();
  25353. /**
  25354. * ShadowGenerators to keep.
  25355. */
  25356. this.shadowGenerators = new Array();
  25357. /**
  25358. * ActionManagers to keep.
  25359. */
  25360. this.actionManagers = new Array();
  25361. /**
  25362. * Sounds to keep.
  25363. */
  25364. this.sounds = new Array();
  25365. }
  25366. return KeepAssets;
  25367. }());
  25368. BABYLON.KeepAssets = KeepAssets;
  25369. /**
  25370. * Container with a set of assets that can be added or removed from a scene.
  25371. */
  25372. var AssetContainer = /** @class */ (function () {
  25373. /**
  25374. * Instantiates an AssetContainer.
  25375. * @param scene The scene the AssetContainer belongs to.
  25376. */
  25377. function AssetContainer(scene) {
  25378. // Objects
  25379. /**
  25380. * Cameras populated in the container.
  25381. */
  25382. this.cameras = new Array();
  25383. /**
  25384. * Lights populated in the container.
  25385. */
  25386. this.lights = new Array();
  25387. /**
  25388. * Meshes populated in the container.
  25389. */
  25390. this.meshes = new Array();
  25391. /**
  25392. * Skeletons populated in the container.
  25393. */
  25394. this.skeletons = new Array();
  25395. /**
  25396. * ParticleSystems populated in the container.
  25397. */
  25398. this.particleSystems = new Array();
  25399. /**
  25400. * Animations populated in the container.
  25401. */
  25402. this.animations = new Array();
  25403. /**
  25404. * MultiMaterials populated in the container.
  25405. */
  25406. this.multiMaterials = new Array();
  25407. /**
  25408. * Materials populated in the container.
  25409. */
  25410. this.materials = new Array();
  25411. /**
  25412. * MorphTargetManagers populated in the container.
  25413. */
  25414. this.morphTargetManagers = new Array();
  25415. /**
  25416. * Geometries populated in the container.
  25417. */
  25418. this.geometries = new Array();
  25419. /**
  25420. * TransformNodes populated in the container.
  25421. */
  25422. this.transformNodes = new Array();
  25423. /**
  25424. * LensFlareSystems populated in the container.
  25425. */
  25426. this.lensFlareSystems = new Array();
  25427. /**
  25428. * ShadowGenerators populated in the container.
  25429. */
  25430. this.shadowGenerators = new Array();
  25431. /**
  25432. * ActionManagers populated in the container.
  25433. */
  25434. this.actionManagers = new Array();
  25435. /**
  25436. * Sounds populated in the container.
  25437. */
  25438. this.sounds = new Array();
  25439. this.scene = scene;
  25440. }
  25441. /**
  25442. * Adds all the assets from the container to the scene.
  25443. */
  25444. AssetContainer.prototype.addAllToScene = function () {
  25445. var _this = this;
  25446. this.cameras.forEach(function (o) {
  25447. _this.scene.addCamera(o);
  25448. });
  25449. this.lights.forEach(function (o) {
  25450. _this.scene.addLight(o);
  25451. });
  25452. this.meshes.forEach(function (o) {
  25453. _this.scene.addMesh(o);
  25454. });
  25455. this.skeletons.forEach(function (o) {
  25456. _this.scene.addSkeleton(o);
  25457. });
  25458. this.particleSystems.forEach(function (o) {
  25459. _this.scene.addParticleSystem(o);
  25460. });
  25461. this.animations.forEach(function (o) {
  25462. _this.scene.addAnimation(o);
  25463. });
  25464. this.multiMaterials.forEach(function (o) {
  25465. _this.scene.addMultiMaterial(o);
  25466. });
  25467. this.materials.forEach(function (o) {
  25468. _this.scene.addMaterial(o);
  25469. });
  25470. this.morphTargetManagers.forEach(function (o) {
  25471. _this.scene.addMorphTargetManager(o);
  25472. });
  25473. this.geometries.forEach(function (o) {
  25474. _this.scene.addGeometry(o);
  25475. });
  25476. this.transformNodes.forEach(function (o) {
  25477. _this.scene.addTransformNode(o);
  25478. });
  25479. this.lensFlareSystems.forEach(function (o) {
  25480. _this.scene.addLensFlareSystem(o);
  25481. });
  25482. this.actionManagers.forEach(function (o) {
  25483. _this.scene.addActionManager(o);
  25484. });
  25485. this.sounds.forEach(function (o) {
  25486. o.play();
  25487. o.autoplay = true;
  25488. _this.scene.mainSoundTrack.AddSound(o);
  25489. });
  25490. };
  25491. /**
  25492. * Removes all the assets in the container from the scene
  25493. */
  25494. AssetContainer.prototype.removeAllFromScene = function () {
  25495. var _this = this;
  25496. this.cameras.forEach(function (o) {
  25497. _this.scene.removeCamera(o);
  25498. });
  25499. this.lights.forEach(function (o) {
  25500. _this.scene.removeLight(o);
  25501. });
  25502. this.meshes.forEach(function (o) {
  25503. _this.scene.removeMesh(o);
  25504. });
  25505. this.skeletons.forEach(function (o) {
  25506. _this.scene.removeSkeleton(o);
  25507. });
  25508. this.particleSystems.forEach(function (o) {
  25509. _this.scene.removeParticleSystem(o);
  25510. });
  25511. this.animations.forEach(function (o) {
  25512. _this.scene.removeAnimation(o);
  25513. });
  25514. this.multiMaterials.forEach(function (o) {
  25515. _this.scene.removeMultiMaterial(o);
  25516. });
  25517. this.materials.forEach(function (o) {
  25518. _this.scene.removeMaterial(o);
  25519. });
  25520. this.morphTargetManagers.forEach(function (o) {
  25521. _this.scene.removeMorphTargetManager(o);
  25522. });
  25523. this.geometries.forEach(function (o) {
  25524. _this.scene.removeGeometry(o);
  25525. });
  25526. this.transformNodes.forEach(function (o) {
  25527. _this.scene.removeTransformNode(o);
  25528. });
  25529. this.lensFlareSystems.forEach(function (o) {
  25530. _this.scene.removeLensFlareSystem(o);
  25531. });
  25532. this.actionManagers.forEach(function (o) {
  25533. _this.scene.removeActionManager(o);
  25534. });
  25535. this.sounds.forEach(function (o) {
  25536. o.stop();
  25537. o.autoplay = false;
  25538. _this.scene.mainSoundTrack.RemoveSound(o);
  25539. });
  25540. };
  25541. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  25542. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  25543. var asset = sourceAssets_1[_i];
  25544. var move = true;
  25545. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  25546. var keepAsset = keepAssets_1[_a];
  25547. if (asset === keepAsset) {
  25548. move = false;
  25549. break;
  25550. }
  25551. }
  25552. if (move) {
  25553. targetAssets.push(asset);
  25554. }
  25555. }
  25556. };
  25557. /**
  25558. * Removes all the assets contained in the scene and adds them to the container.
  25559. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  25560. */
  25561. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  25562. if (keepAssets === undefined) {
  25563. keepAssets = new KeepAssets();
  25564. }
  25565. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  25566. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  25567. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  25568. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  25569. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  25570. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  25571. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  25572. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  25573. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  25574. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  25575. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  25576. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  25577. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  25578. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  25579. this.removeAllFromScene();
  25580. };
  25581. return AssetContainer;
  25582. }());
  25583. BABYLON.AssetContainer = AssetContainer;
  25584. })(BABYLON || (BABYLON = {}));
  25585. //# sourceMappingURL=babylon.assetContainer.js.map
  25586. var BABYLON;
  25587. (function (BABYLON) {
  25588. var Buffer = /** @class */ (function () {
  25589. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  25590. if (instanced === void 0) { instanced = false; }
  25591. if (engine instanceof BABYLON.Mesh) {
  25592. this._engine = engine.getScene().getEngine();
  25593. }
  25594. else {
  25595. this._engine = engine;
  25596. }
  25597. this._updatable = updatable;
  25598. this._instanced = instanced;
  25599. this._data = data;
  25600. this._strideSize = stride;
  25601. if (!postponeInternalCreation) {
  25602. this.create();
  25603. }
  25604. }
  25605. /**
  25606. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  25607. * @param kind defines the vertex buffer kind (position, normal, etc.)
  25608. * @param offset defines offset in the buffer (0 by default)
  25609. * @param size defines the size in floats of attributes (position is 3 for instance)
  25610. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  25611. * @param instanced defines if the vertex buffer contains indexed data
  25612. * @returns the new vertex buffer
  25613. */
  25614. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  25615. // a lot of these parameters are ignored as they are overriden by the buffer
  25616. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  25617. };
  25618. // Properties
  25619. Buffer.prototype.isUpdatable = function () {
  25620. return this._updatable;
  25621. };
  25622. Buffer.prototype.getData = function () {
  25623. return this._data;
  25624. };
  25625. Buffer.prototype.getBuffer = function () {
  25626. return this._buffer;
  25627. };
  25628. Buffer.prototype.getStrideSize = function () {
  25629. return this._strideSize;
  25630. };
  25631. // public getIsInstanced(): boolean {
  25632. // return this._instanced;
  25633. // }
  25634. // public get instanceDivisor(): number {
  25635. // return this._instanceDivisor;
  25636. // }
  25637. // public set instanceDivisor(value: number) {
  25638. // this._instanceDivisor = value;
  25639. // if (value == 0) {
  25640. // this._instanced = false;
  25641. // } else {
  25642. // this._instanced = true;
  25643. // }
  25644. // }
  25645. // Methods
  25646. Buffer.prototype.create = function (data) {
  25647. if (data === void 0) { data = null; }
  25648. if (!data && this._buffer) {
  25649. return; // nothing to do
  25650. }
  25651. data = data || this._data;
  25652. if (!data) {
  25653. return;
  25654. }
  25655. if (!this._buffer) {
  25656. if (this._updatable) {
  25657. this._buffer = this._engine.createDynamicVertexBuffer(data);
  25658. this._data = data;
  25659. }
  25660. else {
  25661. this._buffer = this._engine.createVertexBuffer(data);
  25662. }
  25663. }
  25664. else if (this._updatable) {
  25665. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  25666. this._data = data;
  25667. }
  25668. };
  25669. Buffer.prototype._rebuild = function () {
  25670. this._buffer = null;
  25671. this.create(this._data);
  25672. };
  25673. Buffer.prototype.update = function (data) {
  25674. this.create(data);
  25675. };
  25676. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  25677. if (!this._buffer) {
  25678. return;
  25679. }
  25680. if (this._updatable) {
  25681. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  25682. this._data = null;
  25683. }
  25684. };
  25685. Buffer.prototype.dispose = function () {
  25686. if (!this._buffer) {
  25687. return;
  25688. }
  25689. if (this._engine._releaseBuffer(this._buffer)) {
  25690. this._buffer = null;
  25691. }
  25692. };
  25693. return Buffer;
  25694. }());
  25695. BABYLON.Buffer = Buffer;
  25696. })(BABYLON || (BABYLON = {}));
  25697. //# sourceMappingURL=babylon.buffer.js.map
  25698. var BABYLON;
  25699. (function (BABYLON) {
  25700. var VertexBuffer = /** @class */ (function () {
  25701. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  25702. if (data instanceof BABYLON.Buffer) {
  25703. if (!stride) {
  25704. stride = data.getStrideSize();
  25705. }
  25706. this._buffer = data;
  25707. this._ownsBuffer = false;
  25708. }
  25709. else {
  25710. if (!stride) {
  25711. stride = VertexBuffer.DeduceStride(kind);
  25712. }
  25713. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  25714. this._ownsBuffer = true;
  25715. }
  25716. this._stride = stride;
  25717. this._instanced = instanced !== undefined ? instanced : false;
  25718. this._instanceDivisor = instanced ? 1 : 0;
  25719. this._offset = offset ? offset : 0;
  25720. this._size = size ? size : stride;
  25721. this._kind = kind;
  25722. }
  25723. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  25724. /**
  25725. * Gets or sets the instance divisor when in instanced mode
  25726. */
  25727. get: function () {
  25728. return this._instanceDivisor;
  25729. },
  25730. set: function (value) {
  25731. this._instanceDivisor = value;
  25732. if (value == 0) {
  25733. this._instanced = false;
  25734. }
  25735. else {
  25736. this._instanced = true;
  25737. }
  25738. },
  25739. enumerable: true,
  25740. configurable: true
  25741. });
  25742. VertexBuffer.prototype._rebuild = function () {
  25743. if (!this._buffer) {
  25744. return;
  25745. }
  25746. this._buffer._rebuild();
  25747. };
  25748. /**
  25749. * Returns the kind of the VertexBuffer (string).
  25750. */
  25751. VertexBuffer.prototype.getKind = function () {
  25752. return this._kind;
  25753. };
  25754. // Properties
  25755. /**
  25756. * Boolean : is the VertexBuffer updatable ?
  25757. */
  25758. VertexBuffer.prototype.isUpdatable = function () {
  25759. return this._buffer.isUpdatable();
  25760. };
  25761. /**
  25762. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  25763. */
  25764. VertexBuffer.prototype.getData = function () {
  25765. return this._buffer.getData();
  25766. };
  25767. /**
  25768. * Returns the WebGLBuffer associated to the VertexBuffer.
  25769. */
  25770. VertexBuffer.prototype.getBuffer = function () {
  25771. return this._buffer.getBuffer();
  25772. };
  25773. /**
  25774. * Returns the stride of the VertexBuffer (integer).
  25775. */
  25776. VertexBuffer.prototype.getStrideSize = function () {
  25777. return this._stride;
  25778. };
  25779. /**
  25780. * Returns the offset (integer).
  25781. */
  25782. VertexBuffer.prototype.getOffset = function () {
  25783. return this._offset;
  25784. };
  25785. /**
  25786. * Returns the VertexBuffer total size (integer).
  25787. */
  25788. VertexBuffer.prototype.getSize = function () {
  25789. return this._size;
  25790. };
  25791. /**
  25792. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  25793. */
  25794. VertexBuffer.prototype.getIsInstanced = function () {
  25795. return this._instanced;
  25796. };
  25797. /**
  25798. * Returns the instancing divisor, zero for non-instanced (integer).
  25799. */
  25800. VertexBuffer.prototype.getInstanceDivisor = function () {
  25801. return this._instanceDivisor;
  25802. };
  25803. // Methods
  25804. /**
  25805. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  25806. * Returns the created WebGLBuffer.
  25807. */
  25808. VertexBuffer.prototype.create = function (data) {
  25809. return this._buffer.create(data);
  25810. };
  25811. /**
  25812. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25813. * This function will create a new buffer if the current one is not updatable
  25814. * Returns the updated WebGLBuffer.
  25815. */
  25816. VertexBuffer.prototype.update = function (data) {
  25817. return this._buffer.update(data);
  25818. };
  25819. /**
  25820. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25821. * Returns the directly updated WebGLBuffer.
  25822. */
  25823. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  25824. return this._buffer.updateDirectly(data, offset);
  25825. };
  25826. /**
  25827. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  25828. */
  25829. VertexBuffer.prototype.dispose = function () {
  25830. if (this._ownsBuffer) {
  25831. this._buffer.dispose();
  25832. }
  25833. };
  25834. Object.defineProperty(VertexBuffer, "PositionKind", {
  25835. get: function () {
  25836. return VertexBuffer._PositionKind;
  25837. },
  25838. enumerable: true,
  25839. configurable: true
  25840. });
  25841. Object.defineProperty(VertexBuffer, "NormalKind", {
  25842. get: function () {
  25843. return VertexBuffer._NormalKind;
  25844. },
  25845. enumerable: true,
  25846. configurable: true
  25847. });
  25848. Object.defineProperty(VertexBuffer, "TangentKind", {
  25849. get: function () {
  25850. return VertexBuffer._TangentKind;
  25851. },
  25852. enumerable: true,
  25853. configurable: true
  25854. });
  25855. Object.defineProperty(VertexBuffer, "UVKind", {
  25856. get: function () {
  25857. return VertexBuffer._UVKind;
  25858. },
  25859. enumerable: true,
  25860. configurable: true
  25861. });
  25862. Object.defineProperty(VertexBuffer, "UV2Kind", {
  25863. get: function () {
  25864. return VertexBuffer._UV2Kind;
  25865. },
  25866. enumerable: true,
  25867. configurable: true
  25868. });
  25869. Object.defineProperty(VertexBuffer, "UV3Kind", {
  25870. get: function () {
  25871. return VertexBuffer._UV3Kind;
  25872. },
  25873. enumerable: true,
  25874. configurable: true
  25875. });
  25876. Object.defineProperty(VertexBuffer, "UV4Kind", {
  25877. get: function () {
  25878. return VertexBuffer._UV4Kind;
  25879. },
  25880. enumerable: true,
  25881. configurable: true
  25882. });
  25883. Object.defineProperty(VertexBuffer, "UV5Kind", {
  25884. get: function () {
  25885. return VertexBuffer._UV5Kind;
  25886. },
  25887. enumerable: true,
  25888. configurable: true
  25889. });
  25890. Object.defineProperty(VertexBuffer, "UV6Kind", {
  25891. get: function () {
  25892. return VertexBuffer._UV6Kind;
  25893. },
  25894. enumerable: true,
  25895. configurable: true
  25896. });
  25897. Object.defineProperty(VertexBuffer, "ColorKind", {
  25898. get: function () {
  25899. return VertexBuffer._ColorKind;
  25900. },
  25901. enumerable: true,
  25902. configurable: true
  25903. });
  25904. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  25905. get: function () {
  25906. return VertexBuffer._MatricesIndicesKind;
  25907. },
  25908. enumerable: true,
  25909. configurable: true
  25910. });
  25911. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  25912. get: function () {
  25913. return VertexBuffer._MatricesWeightsKind;
  25914. },
  25915. enumerable: true,
  25916. configurable: true
  25917. });
  25918. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  25919. get: function () {
  25920. return VertexBuffer._MatricesIndicesExtraKind;
  25921. },
  25922. enumerable: true,
  25923. configurable: true
  25924. });
  25925. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  25926. get: function () {
  25927. return VertexBuffer._MatricesWeightsExtraKind;
  25928. },
  25929. enumerable: true,
  25930. configurable: true
  25931. });
  25932. /**
  25933. * Deduces the stride given a kind.
  25934. * @param kind The kind string to deduce
  25935. * @returns The deduced stride
  25936. */
  25937. VertexBuffer.DeduceStride = function (kind) {
  25938. switch (kind) {
  25939. case VertexBuffer.UVKind:
  25940. case VertexBuffer.UV2Kind:
  25941. case VertexBuffer.UV3Kind:
  25942. case VertexBuffer.UV4Kind:
  25943. case VertexBuffer.UV5Kind:
  25944. case VertexBuffer.UV6Kind:
  25945. return 2;
  25946. case VertexBuffer.NormalKind:
  25947. case VertexBuffer.PositionKind:
  25948. return 3;
  25949. case VertexBuffer.ColorKind:
  25950. case VertexBuffer.MatricesIndicesKind:
  25951. case VertexBuffer.MatricesIndicesExtraKind:
  25952. case VertexBuffer.MatricesWeightsKind:
  25953. case VertexBuffer.MatricesWeightsExtraKind:
  25954. case VertexBuffer.TangentKind:
  25955. return 4;
  25956. default:
  25957. throw new Error("Invalid kind '" + kind + "'");
  25958. }
  25959. };
  25960. // Enums
  25961. VertexBuffer._PositionKind = "position";
  25962. VertexBuffer._NormalKind = "normal";
  25963. VertexBuffer._TangentKind = "tangent";
  25964. VertexBuffer._UVKind = "uv";
  25965. VertexBuffer._UV2Kind = "uv2";
  25966. VertexBuffer._UV3Kind = "uv3";
  25967. VertexBuffer._UV4Kind = "uv4";
  25968. VertexBuffer._UV5Kind = "uv5";
  25969. VertexBuffer._UV6Kind = "uv6";
  25970. VertexBuffer._ColorKind = "color";
  25971. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  25972. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  25973. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  25974. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  25975. return VertexBuffer;
  25976. }());
  25977. BABYLON.VertexBuffer = VertexBuffer;
  25978. })(BABYLON || (BABYLON = {}));
  25979. //# sourceMappingURL=babylon.vertexBuffer.js.map
  25980. var BABYLON;
  25981. (function (BABYLON) {
  25982. /**
  25983. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  25984. */
  25985. var DummyInternalTextureTracker = /** @class */ (function () {
  25986. function DummyInternalTextureTracker() {
  25987. /**
  25988. * Gets or set the previous tracker in the list
  25989. */
  25990. this.previous = null;
  25991. /**
  25992. * Gets or set the next tracker in the list
  25993. */
  25994. this.next = null;
  25995. }
  25996. return DummyInternalTextureTracker;
  25997. }());
  25998. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  25999. })(BABYLON || (BABYLON = {}));
  26000. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26001. var BABYLON;
  26002. (function (BABYLON) {
  26003. /**
  26004. * Class used to store data associated with WebGL texture data for the engine
  26005. * This class should not be used directly
  26006. */
  26007. var InternalTexture = /** @class */ (function () {
  26008. /**
  26009. * Creates a new InternalTexture
  26010. * @param engine defines the engine to use
  26011. * @param dataSource defines the type of data that will be used
  26012. */
  26013. function InternalTexture(engine, dataSource) {
  26014. /**
  26015. * Observable called when the texture is loaded
  26016. */
  26017. this.onLoadedObservable = new BABYLON.Observable();
  26018. /**
  26019. * Gets or set the previous tracker in the list
  26020. */
  26021. this.previous = null;
  26022. /**
  26023. * Gets or set the next tracker in the list
  26024. */
  26025. this.next = null;
  26026. // Private
  26027. /** @ignore */
  26028. this._initialSlot = -1;
  26029. /** @ignore */
  26030. this._designatedSlot = -1;
  26031. /** @ignore */
  26032. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26033. /** @ignore */
  26034. this._comparisonFunction = 0;
  26035. /** @ignore */
  26036. this._references = 1;
  26037. this._engine = engine;
  26038. this._dataSource = dataSource;
  26039. this._webGLTexture = engine._createTexture();
  26040. }
  26041. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26042. /**
  26043. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26044. */
  26045. get: function () {
  26046. return this._dataSource;
  26047. },
  26048. enumerable: true,
  26049. configurable: true
  26050. });
  26051. /**
  26052. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26053. */
  26054. InternalTexture.prototype.incrementReferences = function () {
  26055. this._references++;
  26056. };
  26057. /**
  26058. * Change the size of the texture (not the size of the content)
  26059. * @param width defines the new width
  26060. * @param height defines the new height
  26061. * @param depth defines the new depth (1 by default)
  26062. */
  26063. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26064. if (depth === void 0) { depth = 1; }
  26065. this.width = width;
  26066. this.height = height;
  26067. this.depth = depth;
  26068. this.baseWidth = width;
  26069. this.baseHeight = height;
  26070. this.baseDepth = depth;
  26071. this._size = width * height * depth;
  26072. };
  26073. /** @ignore */
  26074. InternalTexture.prototype._rebuild = function () {
  26075. var _this = this;
  26076. var proxy;
  26077. this.isReady = false;
  26078. this._cachedCoordinatesMode = null;
  26079. this._cachedWrapU = null;
  26080. this._cachedWrapV = null;
  26081. this._cachedAnisotropicFilteringLevel = null;
  26082. switch (this._dataSource) {
  26083. case InternalTexture.DATASOURCE_TEMP:
  26084. return;
  26085. case InternalTexture.DATASOURCE_URL:
  26086. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26087. _this.isReady = true;
  26088. }, null, this._buffer, undefined, this.format);
  26089. proxy._swapAndDie(this);
  26090. return;
  26091. case InternalTexture.DATASOURCE_RAW:
  26092. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26093. proxy._swapAndDie(this);
  26094. this.isReady = true;
  26095. return;
  26096. case InternalTexture.DATASOURCE_RAW3D:
  26097. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26098. proxy._swapAndDie(this);
  26099. this.isReady = true;
  26100. return;
  26101. case InternalTexture.DATASOURCE_DYNAMIC:
  26102. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26103. proxy._swapAndDie(this);
  26104. // The engine will make sure to update content so no need to flag it as isReady = true
  26105. return;
  26106. case InternalTexture.DATASOURCE_RENDERTARGET:
  26107. var options = new BABYLON.RenderTargetCreationOptions();
  26108. options.generateDepthBuffer = this._generateDepthBuffer;
  26109. options.generateMipMaps = this.generateMipMaps;
  26110. options.generateStencilBuffer = this._generateStencilBuffer;
  26111. options.samplingMode = this.samplingMode;
  26112. options.type = this.type;
  26113. if (this.isCube) {
  26114. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26115. }
  26116. else {
  26117. var size = {
  26118. width: this.width,
  26119. height: this.height
  26120. };
  26121. proxy = this._engine.createRenderTargetTexture(size, options);
  26122. }
  26123. proxy._swapAndDie(this);
  26124. this.isReady = true;
  26125. return;
  26126. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26127. var depthTextureOptions = {
  26128. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26129. comparisonFunction: this._comparisonFunction,
  26130. generateStencil: this._generateStencilBuffer,
  26131. };
  26132. if (this.isCube) {
  26133. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26134. }
  26135. else {
  26136. proxy = this._engine.createDepthStencilCubeTexture(this.width, depthTextureOptions);
  26137. }
  26138. proxy._swapAndDie(this);
  26139. this.isReady = true;
  26140. return;
  26141. case InternalTexture.DATASOURCE_CUBE:
  26142. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26143. _this.isReady = true;
  26144. }, null, this.format, this._extension);
  26145. proxy._swapAndDie(this);
  26146. return;
  26147. case InternalTexture.DATASOURCE_CUBERAW:
  26148. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26149. proxy._swapAndDie(this);
  26150. this.isReady = true;
  26151. return;
  26152. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26153. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26154. if (proxy) {
  26155. proxy._swapAndDie(_this);
  26156. }
  26157. _this.isReady = true;
  26158. }, null, this.format, this._extension);
  26159. return;
  26160. }
  26161. };
  26162. InternalTexture.prototype._swapAndDie = function (target) {
  26163. target._webGLTexture = this._webGLTexture;
  26164. if (this._framebuffer) {
  26165. target._framebuffer = this._framebuffer;
  26166. }
  26167. if (this._depthStencilBuffer) {
  26168. target._depthStencilBuffer = this._depthStencilBuffer;
  26169. }
  26170. if (this._lodTextureHigh) {
  26171. if (target._lodTextureHigh) {
  26172. target._lodTextureHigh.dispose();
  26173. }
  26174. target._lodTextureHigh = this._lodTextureHigh;
  26175. }
  26176. if (this._lodTextureMid) {
  26177. if (target._lodTextureMid) {
  26178. target._lodTextureMid.dispose();
  26179. }
  26180. target._lodTextureMid = this._lodTextureMid;
  26181. }
  26182. if (this._lodTextureLow) {
  26183. if (target._lodTextureLow) {
  26184. target._lodTextureLow.dispose();
  26185. }
  26186. target._lodTextureLow = this._lodTextureLow;
  26187. }
  26188. var cache = this._engine.getLoadedTexturesCache();
  26189. var index = cache.indexOf(this);
  26190. if (index !== -1) {
  26191. cache.splice(index, 1);
  26192. }
  26193. };
  26194. /**
  26195. * Dispose the current allocated resources
  26196. */
  26197. InternalTexture.prototype.dispose = function () {
  26198. if (!this._webGLTexture) {
  26199. return;
  26200. }
  26201. this._references--;
  26202. if (this._references === 0) {
  26203. this._engine._releaseTexture(this);
  26204. this._webGLTexture = null;
  26205. this.previous = null;
  26206. this.next = null;
  26207. }
  26208. };
  26209. /**
  26210. * The source of the texture data is unknown
  26211. */
  26212. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26213. /**
  26214. * Texture data comes from an URL
  26215. */
  26216. InternalTexture.DATASOURCE_URL = 1;
  26217. /**
  26218. * Texture data is only used for temporary storage
  26219. */
  26220. InternalTexture.DATASOURCE_TEMP = 2;
  26221. /**
  26222. * Texture data comes from raw data (ArrayBuffer)
  26223. */
  26224. InternalTexture.DATASOURCE_RAW = 3;
  26225. /**
  26226. * Texture content is dynamic (video or dynamic texture)
  26227. */
  26228. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26229. /**
  26230. * Texture content is generated by rendering to it
  26231. */
  26232. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26233. /**
  26234. * Texture content is part of a multi render target process
  26235. */
  26236. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26237. /**
  26238. * Texture data comes from a cube data file
  26239. */
  26240. InternalTexture.DATASOURCE_CUBE = 7;
  26241. /**
  26242. * Texture data comes from a raw cube data
  26243. */
  26244. InternalTexture.DATASOURCE_CUBERAW = 8;
  26245. /**
  26246. * Texture data come from a prefiltered cube data file
  26247. */
  26248. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26249. /**
  26250. * Texture content is raw 3D data
  26251. */
  26252. InternalTexture.DATASOURCE_RAW3D = 10;
  26253. /**
  26254. * Texture content is a depth texture
  26255. */
  26256. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26257. return InternalTexture;
  26258. }());
  26259. BABYLON.InternalTexture = InternalTexture;
  26260. })(BABYLON || (BABYLON = {}));
  26261. //# sourceMappingURL=babylon.internalTexture.js.map
  26262. var BABYLON;
  26263. (function (BABYLON) {
  26264. var BaseTexture = /** @class */ (function () {
  26265. function BaseTexture(scene) {
  26266. this._hasAlpha = false;
  26267. this.getAlphaFromRGB = false;
  26268. this.level = 1;
  26269. this.coordinatesIndex = 0;
  26270. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26271. /**
  26272. * | Value | Type | Description |
  26273. * | ----- | ------------------ | ----------- |
  26274. * | 0 | CLAMP_ADDRESSMODE | |
  26275. * | 1 | WRAP_ADDRESSMODE | |
  26276. * | 2 | MIRROR_ADDRESSMODE | |
  26277. */
  26278. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26279. /**
  26280. * | Value | Type | Description |
  26281. * | ----- | ------------------ | ----------- |
  26282. * | 0 | CLAMP_ADDRESSMODE | |
  26283. * | 1 | WRAP_ADDRESSMODE | |
  26284. * | 2 | MIRROR_ADDRESSMODE | |
  26285. */
  26286. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26287. /**
  26288. * | Value | Type | Description |
  26289. * | ----- | ------------------ | ----------- |
  26290. * | 0 | CLAMP_ADDRESSMODE | |
  26291. * | 1 | WRAP_ADDRESSMODE | |
  26292. * | 2 | MIRROR_ADDRESSMODE | |
  26293. */
  26294. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26295. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26296. this.isCube = false;
  26297. this.is3D = false;
  26298. this.gammaSpace = true;
  26299. this.invertZ = false;
  26300. this.lodLevelInAlpha = false;
  26301. this.lodGenerationOffset = 0.0;
  26302. this.lodGenerationScale = 0.8;
  26303. this.isRenderTarget = false;
  26304. this.animations = new Array();
  26305. /**
  26306. * An event triggered when the texture is disposed.
  26307. * @type {BABYLON.Observable}
  26308. */
  26309. this.onDisposeObservable = new BABYLON.Observable();
  26310. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26311. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26312. if (this._scene) {
  26313. this._scene.textures.push(this);
  26314. }
  26315. this._uid = null;
  26316. }
  26317. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26318. get: function () {
  26319. return this._hasAlpha;
  26320. },
  26321. set: function (value) {
  26322. if (this._hasAlpha === value) {
  26323. return;
  26324. }
  26325. this._hasAlpha = value;
  26326. if (this._scene) {
  26327. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26328. }
  26329. },
  26330. enumerable: true,
  26331. configurable: true
  26332. });
  26333. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26334. get: function () {
  26335. return this._coordinatesMode;
  26336. },
  26337. /**
  26338. * How a texture is mapped.
  26339. *
  26340. * | Value | Type | Description |
  26341. * | ----- | ----------------------------------- | ----------- |
  26342. * | 0 | EXPLICIT_MODE | |
  26343. * | 1 | SPHERICAL_MODE | |
  26344. * | 2 | PLANAR_MODE | |
  26345. * | 3 | CUBIC_MODE | |
  26346. * | 4 | PROJECTION_MODE | |
  26347. * | 5 | SKYBOX_MODE | |
  26348. * | 6 | INVCUBIC_MODE | |
  26349. * | 7 | EQUIRECTANGULAR_MODE | |
  26350. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26351. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26352. */
  26353. set: function (value) {
  26354. if (this._coordinatesMode === value) {
  26355. return;
  26356. }
  26357. this._coordinatesMode = value;
  26358. if (this._scene) {
  26359. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26360. }
  26361. },
  26362. enumerable: true,
  26363. configurable: true
  26364. });
  26365. Object.defineProperty(BaseTexture.prototype, "uid", {
  26366. get: function () {
  26367. if (!this._uid) {
  26368. this._uid = BABYLON.Tools.RandomId();
  26369. }
  26370. return this._uid;
  26371. },
  26372. enumerable: true,
  26373. configurable: true
  26374. });
  26375. BaseTexture.prototype.toString = function () {
  26376. return this.name;
  26377. };
  26378. BaseTexture.prototype.getClassName = function () {
  26379. return "BaseTexture";
  26380. };
  26381. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26382. set: function (callback) {
  26383. if (this._onDisposeObserver) {
  26384. this.onDisposeObservable.remove(this._onDisposeObserver);
  26385. }
  26386. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26387. },
  26388. enumerable: true,
  26389. configurable: true
  26390. });
  26391. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26392. get: function () {
  26393. return true;
  26394. },
  26395. enumerable: true,
  26396. configurable: true
  26397. });
  26398. BaseTexture.prototype.getScene = function () {
  26399. return this._scene;
  26400. };
  26401. BaseTexture.prototype.getTextureMatrix = function () {
  26402. return BABYLON.Matrix.IdentityReadOnly;
  26403. };
  26404. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26405. return BABYLON.Matrix.IdentityReadOnly;
  26406. };
  26407. BaseTexture.prototype.getInternalTexture = function () {
  26408. return this._texture;
  26409. };
  26410. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  26411. return !this.isBlocking || this.isReady();
  26412. };
  26413. BaseTexture.prototype.isReady = function () {
  26414. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26415. this.delayLoad();
  26416. return false;
  26417. }
  26418. if (this._texture) {
  26419. return this._texture.isReady;
  26420. }
  26421. return false;
  26422. };
  26423. BaseTexture.prototype.getSize = function () {
  26424. if (this._texture && this._texture.width) {
  26425. return new BABYLON.Size(this._texture.width, this._texture.height);
  26426. }
  26427. if (this._texture && this._texture._size) {
  26428. return new BABYLON.Size(this._texture._size, this._texture._size);
  26429. }
  26430. return BABYLON.Size.Zero();
  26431. };
  26432. BaseTexture.prototype.getBaseSize = function () {
  26433. if (!this.isReady() || !this._texture)
  26434. return BABYLON.Size.Zero();
  26435. if (this._texture._size) {
  26436. return new BABYLON.Size(this._texture._size, this._texture._size);
  26437. }
  26438. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  26439. };
  26440. BaseTexture.prototype.scale = function (ratio) {
  26441. };
  26442. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26443. get: function () {
  26444. return false;
  26445. },
  26446. enumerable: true,
  26447. configurable: true
  26448. });
  26449. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  26450. if (!this._scene) {
  26451. return null;
  26452. }
  26453. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26454. for (var index = 0; index < texturesCache.length; index++) {
  26455. var texturesCacheEntry = texturesCache[index];
  26456. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  26457. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  26458. texturesCacheEntry.incrementReferences();
  26459. return texturesCacheEntry;
  26460. }
  26461. }
  26462. }
  26463. return null;
  26464. };
  26465. BaseTexture.prototype._rebuild = function () {
  26466. };
  26467. BaseTexture.prototype.delayLoad = function () {
  26468. };
  26469. BaseTexture.prototype.clone = function () {
  26470. return null;
  26471. };
  26472. Object.defineProperty(BaseTexture.prototype, "textureType", {
  26473. get: function () {
  26474. if (!this._texture) {
  26475. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26476. }
  26477. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26478. },
  26479. enumerable: true,
  26480. configurable: true
  26481. });
  26482. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  26483. get: function () {
  26484. if (!this._texture) {
  26485. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26486. }
  26487. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26488. },
  26489. enumerable: true,
  26490. configurable: true
  26491. });
  26492. BaseTexture.prototype.readPixels = function (faceIndex) {
  26493. if (faceIndex === void 0) { faceIndex = 0; }
  26494. if (!this._texture) {
  26495. return null;
  26496. }
  26497. var size = this.getSize();
  26498. var scene = this.getScene();
  26499. if (!scene) {
  26500. return null;
  26501. }
  26502. var engine = scene.getEngine();
  26503. if (this._texture.isCube) {
  26504. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  26505. }
  26506. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  26507. };
  26508. BaseTexture.prototype.releaseInternalTexture = function () {
  26509. if (this._texture) {
  26510. this._texture.dispose();
  26511. this._texture = null;
  26512. }
  26513. };
  26514. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  26515. get: function () {
  26516. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  26517. return null;
  26518. }
  26519. if (!this._texture._sphericalPolynomial) {
  26520. this._texture._sphericalPolynomial =
  26521. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  26522. }
  26523. return this._texture._sphericalPolynomial;
  26524. },
  26525. set: function (value) {
  26526. if (this._texture) {
  26527. this._texture._sphericalPolynomial = value;
  26528. }
  26529. },
  26530. enumerable: true,
  26531. configurable: true
  26532. });
  26533. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  26534. get: function () {
  26535. if (this._texture) {
  26536. return this._texture._lodTextureHigh;
  26537. }
  26538. return null;
  26539. },
  26540. enumerable: true,
  26541. configurable: true
  26542. });
  26543. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  26544. get: function () {
  26545. if (this._texture) {
  26546. return this._texture._lodTextureMid;
  26547. }
  26548. return null;
  26549. },
  26550. enumerable: true,
  26551. configurable: true
  26552. });
  26553. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  26554. get: function () {
  26555. if (this._texture) {
  26556. return this._texture._lodTextureLow;
  26557. }
  26558. return null;
  26559. },
  26560. enumerable: true,
  26561. configurable: true
  26562. });
  26563. BaseTexture.prototype.dispose = function () {
  26564. if (!this._scene) {
  26565. return;
  26566. }
  26567. // Animations
  26568. this._scene.stopAnimation(this);
  26569. // Remove from scene
  26570. this._scene._removePendingData(this);
  26571. var index = this._scene.textures.indexOf(this);
  26572. if (index >= 0) {
  26573. this._scene.textures.splice(index, 1);
  26574. }
  26575. if (this._texture === undefined) {
  26576. return;
  26577. }
  26578. // Release
  26579. this.releaseInternalTexture();
  26580. // Callback
  26581. this.onDisposeObservable.notifyObservers(this);
  26582. this.onDisposeObservable.clear();
  26583. };
  26584. BaseTexture.prototype.serialize = function () {
  26585. if (!this.name) {
  26586. return null;
  26587. }
  26588. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26589. // Animations
  26590. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26591. return serializationObject;
  26592. };
  26593. BaseTexture.WhenAllReady = function (textures, callback) {
  26594. var numRemaining = textures.length;
  26595. if (numRemaining === 0) {
  26596. callback();
  26597. return;
  26598. }
  26599. var _loop_1 = function () {
  26600. texture = textures[i];
  26601. if (texture.isReady()) {
  26602. if (--numRemaining === 0) {
  26603. callback();
  26604. }
  26605. }
  26606. else {
  26607. onLoadObservable = texture.onLoadObservable;
  26608. var onLoadCallback_1 = function () {
  26609. onLoadObservable.removeCallback(onLoadCallback_1);
  26610. if (--numRemaining === 0) {
  26611. callback();
  26612. }
  26613. };
  26614. onLoadObservable.add(onLoadCallback_1);
  26615. }
  26616. };
  26617. var texture, onLoadObservable;
  26618. for (var i = 0; i < textures.length; i++) {
  26619. _loop_1();
  26620. }
  26621. };
  26622. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  26623. __decorate([
  26624. BABYLON.serialize()
  26625. ], BaseTexture.prototype, "name", void 0);
  26626. __decorate([
  26627. BABYLON.serialize("hasAlpha")
  26628. ], BaseTexture.prototype, "_hasAlpha", void 0);
  26629. __decorate([
  26630. BABYLON.serialize()
  26631. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26632. __decorate([
  26633. BABYLON.serialize()
  26634. ], BaseTexture.prototype, "level", void 0);
  26635. __decorate([
  26636. BABYLON.serialize()
  26637. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26638. __decorate([
  26639. BABYLON.serialize("coordinatesMode")
  26640. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  26641. __decorate([
  26642. BABYLON.serialize()
  26643. ], BaseTexture.prototype, "wrapU", void 0);
  26644. __decorate([
  26645. BABYLON.serialize()
  26646. ], BaseTexture.prototype, "wrapV", void 0);
  26647. __decorate([
  26648. BABYLON.serialize()
  26649. ], BaseTexture.prototype, "wrapR", void 0);
  26650. __decorate([
  26651. BABYLON.serialize()
  26652. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26653. __decorate([
  26654. BABYLON.serialize()
  26655. ], BaseTexture.prototype, "isCube", void 0);
  26656. __decorate([
  26657. BABYLON.serialize()
  26658. ], BaseTexture.prototype, "is3D", void 0);
  26659. __decorate([
  26660. BABYLON.serialize()
  26661. ], BaseTexture.prototype, "gammaSpace", void 0);
  26662. __decorate([
  26663. BABYLON.serialize()
  26664. ], BaseTexture.prototype, "invertZ", void 0);
  26665. __decorate([
  26666. BABYLON.serialize()
  26667. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  26668. __decorate([
  26669. BABYLON.serialize()
  26670. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  26671. __decorate([
  26672. BABYLON.serialize()
  26673. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  26674. __decorate([
  26675. BABYLON.serialize()
  26676. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26677. return BaseTexture;
  26678. }());
  26679. BABYLON.BaseTexture = BaseTexture;
  26680. })(BABYLON || (BABYLON = {}));
  26681. //# sourceMappingURL=babylon.baseTexture.js.map
  26682. var BABYLON;
  26683. (function (BABYLON) {
  26684. var Texture = /** @class */ (function (_super) {
  26685. __extends(Texture, _super);
  26686. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26687. if (noMipmap === void 0) { noMipmap = false; }
  26688. if (invertY === void 0) { invertY = true; }
  26689. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26690. if (onLoad === void 0) { onLoad = null; }
  26691. if (onError === void 0) { onError = null; }
  26692. if (buffer === void 0) { buffer = null; }
  26693. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26694. var _this = _super.call(this, scene) || this;
  26695. _this.uOffset = 0;
  26696. _this.vOffset = 0;
  26697. _this.uScale = 1.0;
  26698. _this.vScale = 1.0;
  26699. _this.uAng = 0;
  26700. _this.vAng = 0;
  26701. _this.wAng = 0;
  26702. _this._isBlocking = true;
  26703. _this.name = url || "";
  26704. _this.url = url;
  26705. _this._noMipmap = noMipmap;
  26706. _this._invertY = invertY;
  26707. _this._samplingMode = samplingMode;
  26708. _this._buffer = buffer;
  26709. _this._deleteBuffer = deleteBuffer;
  26710. if (format) {
  26711. _this._format = format;
  26712. }
  26713. scene = _this.getScene();
  26714. if (!scene) {
  26715. return _this;
  26716. }
  26717. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  26718. var load = function () {
  26719. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  26720. _this.onLoadObservable.notifyObservers(_this);
  26721. }
  26722. if (onLoad) {
  26723. onLoad();
  26724. }
  26725. if (!_this.isBlocking && scene) {
  26726. scene.resetCachedMaterial();
  26727. }
  26728. };
  26729. if (!_this.url) {
  26730. _this._delayedOnLoad = load;
  26731. _this._delayedOnError = onError;
  26732. return _this;
  26733. }
  26734. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  26735. if (!_this._texture) {
  26736. if (!scene.useDelayedTextureLoading) {
  26737. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  26738. if (deleteBuffer) {
  26739. delete _this._buffer;
  26740. }
  26741. }
  26742. else {
  26743. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26744. _this._delayedOnLoad = load;
  26745. _this._delayedOnError = onError;
  26746. }
  26747. }
  26748. else {
  26749. if (_this._texture.isReady) {
  26750. BABYLON.Tools.SetImmediate(function () { return load(); });
  26751. }
  26752. else {
  26753. _this._texture.onLoadedObservable.add(load);
  26754. }
  26755. }
  26756. return _this;
  26757. }
  26758. Object.defineProperty(Texture.prototype, "noMipmap", {
  26759. get: function () {
  26760. return this._noMipmap;
  26761. },
  26762. enumerable: true,
  26763. configurable: true
  26764. });
  26765. Object.defineProperty(Texture.prototype, "isBlocking", {
  26766. get: function () {
  26767. return this._isBlocking;
  26768. },
  26769. set: function (value) {
  26770. this._isBlocking = value;
  26771. },
  26772. enumerable: true,
  26773. configurable: true
  26774. });
  26775. Object.defineProperty(Texture.prototype, "samplingMode", {
  26776. get: function () {
  26777. return this._samplingMode;
  26778. },
  26779. enumerable: true,
  26780. configurable: true
  26781. });
  26782. Texture.prototype.updateURL = function (url) {
  26783. this.url = url;
  26784. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26785. this.delayLoad();
  26786. };
  26787. Texture.prototype.delayLoad = function () {
  26788. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26789. return;
  26790. }
  26791. var scene = this.getScene();
  26792. if (!scene) {
  26793. return;
  26794. }
  26795. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26796. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  26797. if (!this._texture) {
  26798. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  26799. if (this._deleteBuffer) {
  26800. delete this._buffer;
  26801. }
  26802. }
  26803. else {
  26804. if (this._delayedOnLoad) {
  26805. if (this._texture.isReady) {
  26806. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  26807. }
  26808. else {
  26809. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  26810. }
  26811. }
  26812. }
  26813. this._delayedOnLoad = null;
  26814. this._delayedOnError = null;
  26815. };
  26816. Texture.prototype.updateSamplingMode = function (samplingMode) {
  26817. if (!this._texture) {
  26818. return;
  26819. }
  26820. var scene = this.getScene();
  26821. if (!scene) {
  26822. return;
  26823. }
  26824. this._samplingMode = samplingMode;
  26825. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  26826. };
  26827. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  26828. x *= this.uScale;
  26829. y *= this.vScale;
  26830. x -= 0.5 * this.uScale;
  26831. y -= 0.5 * this.vScale;
  26832. z -= 0.5;
  26833. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  26834. t.x += 0.5 * this.uScale + this.uOffset;
  26835. t.y += 0.5 * this.vScale + this.vOffset;
  26836. t.z += 0.5;
  26837. };
  26838. Texture.prototype.getTextureMatrix = function () {
  26839. var _this = this;
  26840. if (this.uOffset === this._cachedUOffset &&
  26841. this.vOffset === this._cachedVOffset &&
  26842. this.uScale === this._cachedUScale &&
  26843. this.vScale === this._cachedVScale &&
  26844. this.uAng === this._cachedUAng &&
  26845. this.vAng === this._cachedVAng &&
  26846. this.wAng === this._cachedWAng) {
  26847. return this._cachedTextureMatrix;
  26848. }
  26849. this._cachedUOffset = this.uOffset;
  26850. this._cachedVOffset = this.vOffset;
  26851. this._cachedUScale = this.uScale;
  26852. this._cachedVScale = this.vScale;
  26853. this._cachedUAng = this.uAng;
  26854. this._cachedVAng = this.vAng;
  26855. this._cachedWAng = this.wAng;
  26856. if (!this._cachedTextureMatrix) {
  26857. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26858. this._rowGenerationMatrix = new BABYLON.Matrix();
  26859. this._t0 = BABYLON.Vector3.Zero();
  26860. this._t1 = BABYLON.Vector3.Zero();
  26861. this._t2 = BABYLON.Vector3.Zero();
  26862. }
  26863. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  26864. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  26865. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  26866. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  26867. this._t1.subtractInPlace(this._t0);
  26868. this._t2.subtractInPlace(this._t0);
  26869. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26870. this._cachedTextureMatrix.m[0] = this._t1.x;
  26871. this._cachedTextureMatrix.m[1] = this._t1.y;
  26872. this._cachedTextureMatrix.m[2] = this._t1.z;
  26873. this._cachedTextureMatrix.m[4] = this._t2.x;
  26874. this._cachedTextureMatrix.m[5] = this._t2.y;
  26875. this._cachedTextureMatrix.m[6] = this._t2.z;
  26876. this._cachedTextureMatrix.m[8] = this._t0.x;
  26877. this._cachedTextureMatrix.m[9] = this._t0.y;
  26878. this._cachedTextureMatrix.m[10] = this._t0.z;
  26879. var scene = this.getScene();
  26880. if (!scene) {
  26881. return this._cachedTextureMatrix;
  26882. }
  26883. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26884. return mat.hasTexture(_this);
  26885. });
  26886. return this._cachedTextureMatrix;
  26887. };
  26888. Texture.prototype.getReflectionTextureMatrix = function () {
  26889. var _this = this;
  26890. var scene = this.getScene();
  26891. if (!scene) {
  26892. return this._cachedTextureMatrix;
  26893. }
  26894. if (this.uOffset === this._cachedUOffset &&
  26895. this.vOffset === this._cachedVOffset &&
  26896. this.uScale === this._cachedUScale &&
  26897. this.vScale === this._cachedVScale &&
  26898. this.coordinatesMode === this._cachedCoordinatesMode) {
  26899. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  26900. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  26901. return this._cachedTextureMatrix;
  26902. }
  26903. }
  26904. else {
  26905. return this._cachedTextureMatrix;
  26906. }
  26907. }
  26908. if (!this._cachedTextureMatrix) {
  26909. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26910. }
  26911. if (!this._projectionModeMatrix) {
  26912. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  26913. }
  26914. this._cachedUOffset = this.uOffset;
  26915. this._cachedVOffset = this.vOffset;
  26916. this._cachedUScale = this.uScale;
  26917. this._cachedVScale = this.vScale;
  26918. this._cachedCoordinatesMode = this.coordinatesMode;
  26919. switch (this.coordinatesMode) {
  26920. case Texture.PLANAR_MODE:
  26921. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26922. this._cachedTextureMatrix[0] = this.uScale;
  26923. this._cachedTextureMatrix[5] = this.vScale;
  26924. this._cachedTextureMatrix[12] = this.uOffset;
  26925. this._cachedTextureMatrix[13] = this.vOffset;
  26926. break;
  26927. case Texture.PROJECTION_MODE:
  26928. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  26929. this._projectionModeMatrix.m[0] = 0.5;
  26930. this._projectionModeMatrix.m[5] = -0.5;
  26931. this._projectionModeMatrix.m[10] = 0.0;
  26932. this._projectionModeMatrix.m[12] = 0.5;
  26933. this._projectionModeMatrix.m[13] = 0.5;
  26934. this._projectionModeMatrix.m[14] = 1.0;
  26935. this._projectionModeMatrix.m[15] = 1.0;
  26936. var projectionMatrix = scene.getProjectionMatrix();
  26937. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  26938. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  26939. break;
  26940. default:
  26941. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26942. break;
  26943. }
  26944. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26945. return (mat.getActiveTextures().indexOf(_this) !== -1);
  26946. });
  26947. return this._cachedTextureMatrix;
  26948. };
  26949. Texture.prototype.clone = function () {
  26950. var _this = this;
  26951. return BABYLON.SerializationHelper.Clone(function () {
  26952. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  26953. }, this);
  26954. };
  26955. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  26956. get: function () {
  26957. if (!this._onLoadObservable) {
  26958. this._onLoadObservable = new BABYLON.Observable();
  26959. }
  26960. return this._onLoadObservable;
  26961. },
  26962. enumerable: true,
  26963. configurable: true
  26964. });
  26965. Texture.prototype.serialize = function () {
  26966. var serializationObject = _super.prototype.serialize.call(this);
  26967. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  26968. serializationObject.base64String = this._buffer;
  26969. serializationObject.name = serializationObject.name.replace("data:", "");
  26970. }
  26971. return serializationObject;
  26972. };
  26973. Texture.prototype.getClassName = function () {
  26974. return "Texture";
  26975. };
  26976. Texture.prototype.dispose = function () {
  26977. _super.prototype.dispose.call(this);
  26978. if (this.onLoadObservable) {
  26979. this.onLoadObservable.clear();
  26980. this._onLoadObservable = null;
  26981. }
  26982. this._delayedOnLoad = null;
  26983. this._delayedOnError = null;
  26984. };
  26985. // Statics
  26986. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26987. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26988. if (onLoad === void 0) { onLoad = null; }
  26989. if (onError === void 0) { onError = null; }
  26990. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26991. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  26992. };
  26993. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  26994. if (parsedTexture.customType) {
  26995. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  26996. // Update Sampling Mode
  26997. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  26998. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  26999. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27000. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27001. }
  27002. }
  27003. return parsedCustomTexture;
  27004. }
  27005. if (parsedTexture.isCube) {
  27006. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27007. }
  27008. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27009. return null;
  27010. }
  27011. var texture = BABYLON.SerializationHelper.Parse(function () {
  27012. var generateMipMaps = true;
  27013. if (parsedTexture.noMipmap) {
  27014. generateMipMaps = false;
  27015. }
  27016. if (parsedTexture.mirrorPlane) {
  27017. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27018. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27019. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27020. return mirrorTexture;
  27021. }
  27022. else if (parsedTexture.isRenderTarget) {
  27023. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27024. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27025. return renderTargetTexture;
  27026. }
  27027. else {
  27028. var texture;
  27029. if (parsedTexture.base64String) {
  27030. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27031. }
  27032. else {
  27033. var url = rootUrl + parsedTexture.name;
  27034. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27035. url = parsedTexture.url;
  27036. }
  27037. texture = new Texture(url, scene, !generateMipMaps);
  27038. }
  27039. return texture;
  27040. }
  27041. }, parsedTexture, scene);
  27042. // Update Sampling Mode
  27043. if (parsedTexture.samplingMode) {
  27044. var sampling = parsedTexture.samplingMode;
  27045. if (texture._samplingMode !== sampling) {
  27046. texture.updateSamplingMode(sampling);
  27047. }
  27048. }
  27049. // Animations
  27050. if (parsedTexture.animations) {
  27051. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27052. var parsedAnimation = parsedTexture.animations[animationIndex];
  27053. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27054. }
  27055. }
  27056. return texture;
  27057. };
  27058. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27059. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27060. if (noMipmap === void 0) { noMipmap = false; }
  27061. if (invertY === void 0) { invertY = true; }
  27062. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27063. if (onLoad === void 0) { onLoad = null; }
  27064. if (onError === void 0) { onError = null; }
  27065. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27066. if (name.substr(0, 5) !== "data:") {
  27067. name = "data:" + name;
  27068. }
  27069. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27070. };
  27071. // Constants
  27072. Texture.NEAREST_SAMPLINGMODE = 1;
  27073. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27074. Texture.BILINEAR_SAMPLINGMODE = 2;
  27075. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27076. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27077. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27078. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27079. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27080. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27081. Texture.NEAREST_LINEAR = 7;
  27082. Texture.NEAREST_NEAREST = 8;
  27083. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27084. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27085. Texture.LINEAR_LINEAR = 11;
  27086. Texture.LINEAR_NEAREST = 12;
  27087. Texture.EXPLICIT_MODE = 0;
  27088. Texture.SPHERICAL_MODE = 1;
  27089. Texture.PLANAR_MODE = 2;
  27090. Texture.CUBIC_MODE = 3;
  27091. Texture.PROJECTION_MODE = 4;
  27092. Texture.SKYBOX_MODE = 5;
  27093. Texture.INVCUBIC_MODE = 6;
  27094. Texture.EQUIRECTANGULAR_MODE = 7;
  27095. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27096. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27097. Texture.CLAMP_ADDRESSMODE = 0;
  27098. Texture.WRAP_ADDRESSMODE = 1;
  27099. Texture.MIRROR_ADDRESSMODE = 2;
  27100. /**
  27101. * 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
  27102. */
  27103. Texture.UseSerializedUrlIfAny = false;
  27104. __decorate([
  27105. BABYLON.serialize()
  27106. ], Texture.prototype, "url", void 0);
  27107. __decorate([
  27108. BABYLON.serialize()
  27109. ], Texture.prototype, "uOffset", void 0);
  27110. __decorate([
  27111. BABYLON.serialize()
  27112. ], Texture.prototype, "vOffset", void 0);
  27113. __decorate([
  27114. BABYLON.serialize()
  27115. ], Texture.prototype, "uScale", void 0);
  27116. __decorate([
  27117. BABYLON.serialize()
  27118. ], Texture.prototype, "vScale", void 0);
  27119. __decorate([
  27120. BABYLON.serialize()
  27121. ], Texture.prototype, "uAng", void 0);
  27122. __decorate([
  27123. BABYLON.serialize()
  27124. ], Texture.prototype, "vAng", void 0);
  27125. __decorate([
  27126. BABYLON.serialize()
  27127. ], Texture.prototype, "wAng", void 0);
  27128. __decorate([
  27129. BABYLON.serialize()
  27130. ], Texture.prototype, "isBlocking", null);
  27131. return Texture;
  27132. }(BABYLON.BaseTexture));
  27133. BABYLON.Texture = Texture;
  27134. })(BABYLON || (BABYLON = {}));
  27135. //# sourceMappingURL=babylon.texture.js.map
  27136. var BABYLON;
  27137. (function (BABYLON) {
  27138. var _InstancesBatch = /** @class */ (function () {
  27139. function _InstancesBatch() {
  27140. this.mustReturn = false;
  27141. this.visibleInstances = new Array();
  27142. this.renderSelf = new Array();
  27143. }
  27144. return _InstancesBatch;
  27145. }());
  27146. BABYLON._InstancesBatch = _InstancesBatch;
  27147. var Mesh = /** @class */ (function (_super) {
  27148. __extends(Mesh, _super);
  27149. /**
  27150. * @constructor
  27151. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27152. * @param {Scene} scene The scene to add this mesh to.
  27153. * @param {Node} parent The parent of this mesh, if it has one
  27154. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27155. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27156. * When false, achieved by calling a clone(), also passing False.
  27157. * This will make creation of children, recursive.
  27158. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27159. */
  27160. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27161. if (scene === void 0) { scene = null; }
  27162. if (parent === void 0) { parent = null; }
  27163. if (source === void 0) { source = null; }
  27164. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27165. var _this = _super.call(this, name, scene) || this;
  27166. // Events
  27167. /**
  27168. * An event triggered before rendering the mesh
  27169. * @type {BABYLON.Observable}
  27170. */
  27171. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27172. /**
  27173. * An event triggered after rendering the mesh
  27174. * @type {BABYLON.Observable}
  27175. */
  27176. _this.onAfterRenderObservable = new BABYLON.Observable();
  27177. /**
  27178. * An event triggered before drawing the mesh
  27179. * @type {BABYLON.Observable}
  27180. */
  27181. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27182. // Members
  27183. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27184. _this.instances = new Array();
  27185. _this._LODLevels = new Array();
  27186. _this._visibleInstances = {};
  27187. _this._renderIdForInstances = new Array();
  27188. _this._batchCache = new _InstancesBatch();
  27189. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27190. // Use by builder only to know what orientation were the mesh build in.
  27191. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27192. _this.overrideMaterialSideOrientation = null;
  27193. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27194. // Will be used to save a source mesh reference, If any
  27195. _this._source = null;
  27196. scene = _this.getScene();
  27197. if (source) {
  27198. // Source mesh
  27199. _this._source = source;
  27200. // Geometry
  27201. if (source._geometry) {
  27202. source._geometry.applyToMesh(_this);
  27203. }
  27204. // Deep copy
  27205. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  27206. // Metadata
  27207. if (source.metadata && source.metadata.clone) {
  27208. _this.metadata = source.metadata.clone();
  27209. }
  27210. else {
  27211. _this.metadata = source.metadata;
  27212. }
  27213. // Tags
  27214. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27215. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27216. }
  27217. // Parent
  27218. _this.parent = source.parent;
  27219. // Pivot
  27220. _this.setPivotMatrix(source.getPivotMatrix());
  27221. _this.id = name + "." + source.id;
  27222. // Material
  27223. _this.material = source.material;
  27224. var index;
  27225. if (!doNotCloneChildren) {
  27226. // Children
  27227. var directDescendants = source.getDescendants(true);
  27228. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27229. var child = directDescendants[index_1];
  27230. if (child.clone) {
  27231. child.clone(name + "." + child.name, _this);
  27232. }
  27233. }
  27234. }
  27235. // Physics clone
  27236. var physicsEngine = _this.getScene().getPhysicsEngine();
  27237. if (clonePhysicsImpostor && physicsEngine) {
  27238. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27239. if (impostor) {
  27240. _this.physicsImpostor = impostor.clone(_this);
  27241. }
  27242. }
  27243. // Particles
  27244. for (index = 0; index < scene.particleSystems.length; index++) {
  27245. var system = scene.particleSystems[index];
  27246. if (system.emitter === source) {
  27247. system.clone(system.name, _this);
  27248. }
  27249. }
  27250. _this.computeWorldMatrix(true);
  27251. }
  27252. // Parent
  27253. if (parent !== null) {
  27254. _this.parent = parent;
  27255. }
  27256. return _this;
  27257. }
  27258. Object.defineProperty(Mesh, "FRONTSIDE", {
  27259. /**
  27260. * Mesh side orientation : usually the external or front surface
  27261. */
  27262. get: function () {
  27263. return Mesh._FRONTSIDE;
  27264. },
  27265. enumerable: true,
  27266. configurable: true
  27267. });
  27268. Object.defineProperty(Mesh, "BACKSIDE", {
  27269. /**
  27270. * Mesh side orientation : usually the internal or back surface
  27271. */
  27272. get: function () {
  27273. return Mesh._BACKSIDE;
  27274. },
  27275. enumerable: true,
  27276. configurable: true
  27277. });
  27278. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27279. /**
  27280. * Mesh side orientation : both internal and external or front and back surfaces
  27281. */
  27282. get: function () {
  27283. return Mesh._DOUBLESIDE;
  27284. },
  27285. enumerable: true,
  27286. configurable: true
  27287. });
  27288. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27289. /**
  27290. * Mesh side orientation : by default, `FRONTSIDE`
  27291. */
  27292. get: function () {
  27293. return Mesh._DEFAULTSIDE;
  27294. },
  27295. enumerable: true,
  27296. configurable: true
  27297. });
  27298. Object.defineProperty(Mesh, "NO_CAP", {
  27299. /**
  27300. * Mesh cap setting : no cap
  27301. */
  27302. get: function () {
  27303. return Mesh._NO_CAP;
  27304. },
  27305. enumerable: true,
  27306. configurable: true
  27307. });
  27308. Object.defineProperty(Mesh, "CAP_START", {
  27309. /**
  27310. * Mesh cap setting : one cap at the beginning of the mesh
  27311. */
  27312. get: function () {
  27313. return Mesh._CAP_START;
  27314. },
  27315. enumerable: true,
  27316. configurable: true
  27317. });
  27318. Object.defineProperty(Mesh, "CAP_END", {
  27319. /**
  27320. * Mesh cap setting : one cap at the end of the mesh
  27321. */
  27322. get: function () {
  27323. return Mesh._CAP_END;
  27324. },
  27325. enumerable: true,
  27326. configurable: true
  27327. });
  27328. Object.defineProperty(Mesh, "CAP_ALL", {
  27329. /**
  27330. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27331. */
  27332. get: function () {
  27333. return Mesh._CAP_ALL;
  27334. },
  27335. enumerable: true,
  27336. configurable: true
  27337. });
  27338. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27339. set: function (callback) {
  27340. if (this._onBeforeDrawObserver) {
  27341. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27342. }
  27343. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27344. },
  27345. enumerable: true,
  27346. configurable: true
  27347. });
  27348. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27349. get: function () {
  27350. return this._morphTargetManager;
  27351. },
  27352. set: function (value) {
  27353. if (this._morphTargetManager === value) {
  27354. return;
  27355. }
  27356. this._morphTargetManager = value;
  27357. this._syncGeometryWithMorphTargetManager();
  27358. },
  27359. enumerable: true,
  27360. configurable: true
  27361. });
  27362. Object.defineProperty(Mesh.prototype, "source", {
  27363. get: function () {
  27364. return this._source;
  27365. },
  27366. enumerable: true,
  27367. configurable: true
  27368. });
  27369. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27370. get: function () {
  27371. return this._unIndexed;
  27372. },
  27373. set: function (value) {
  27374. if (this._unIndexed !== value) {
  27375. this._unIndexed = value;
  27376. this._markSubMeshesAsAttributesDirty();
  27377. }
  27378. },
  27379. enumerable: true,
  27380. configurable: true
  27381. });
  27382. // Methods
  27383. /**
  27384. * Returns the string "Mesh".
  27385. */
  27386. Mesh.prototype.getClassName = function () {
  27387. return "Mesh";
  27388. };
  27389. /**
  27390. * Returns a string.
  27391. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27392. */
  27393. Mesh.prototype.toString = function (fullDetails) {
  27394. var ret = _super.prototype.toString.call(this, fullDetails);
  27395. ret += ", n vertices: " + this.getTotalVertices();
  27396. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27397. if (this.animations) {
  27398. for (var i = 0; i < this.animations.length; i++) {
  27399. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  27400. }
  27401. }
  27402. if (fullDetails) {
  27403. if (this._geometry) {
  27404. var ib = this.getIndices();
  27405. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27406. if (vb && ib) {
  27407. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  27408. }
  27409. }
  27410. else {
  27411. ret += ", flat shading: UNKNOWN";
  27412. }
  27413. }
  27414. return ret;
  27415. };
  27416. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  27417. /**
  27418. * True if the mesh has some Levels Of Details (LOD).
  27419. * Returns a boolean.
  27420. */
  27421. get: function () {
  27422. return this._LODLevels.length > 0;
  27423. },
  27424. enumerable: true,
  27425. configurable: true
  27426. });
  27427. /**
  27428. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  27429. * @returns an array of {BABYLON.MeshLODLevel}
  27430. */
  27431. Mesh.prototype.getLODLevels = function () {
  27432. return this._LODLevels;
  27433. };
  27434. Mesh.prototype._sortLODLevels = function () {
  27435. this._LODLevels.sort(function (a, b) {
  27436. if (a.distance < b.distance) {
  27437. return 1;
  27438. }
  27439. if (a.distance > b.distance) {
  27440. return -1;
  27441. }
  27442. return 0;
  27443. });
  27444. };
  27445. /**
  27446. * Add a mesh as LOD level triggered at the given distance.
  27447. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27448. * @param {number} distance The distance from the center of the object to show this level
  27449. * @param {Mesh} mesh The mesh to be added as LOD level
  27450. * @return {Mesh} This mesh (for chaining)
  27451. */
  27452. Mesh.prototype.addLODLevel = function (distance, mesh) {
  27453. if (mesh && mesh._masterMesh) {
  27454. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  27455. return this;
  27456. }
  27457. var level = new BABYLON.MeshLODLevel(distance, mesh);
  27458. this._LODLevels.push(level);
  27459. if (mesh) {
  27460. mesh._masterMesh = this;
  27461. }
  27462. this._sortLODLevels();
  27463. return this;
  27464. };
  27465. /**
  27466. * Returns the LOD level mesh at the passed distance or null if not found.
  27467. * It is related to the method `addLODLevel(distance, mesh)`.
  27468. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27469. * Returns an object Mesh or `null`.
  27470. */
  27471. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  27472. for (var index = 0; index < this._LODLevels.length; index++) {
  27473. var level = this._LODLevels[index];
  27474. if (level.distance === distance) {
  27475. return level.mesh;
  27476. }
  27477. }
  27478. return null;
  27479. };
  27480. /**
  27481. * Remove a mesh from the LOD array
  27482. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27483. * @param {Mesh} mesh The mesh to be removed.
  27484. * @return {Mesh} This mesh (for chaining)
  27485. */
  27486. Mesh.prototype.removeLODLevel = function (mesh) {
  27487. for (var index = 0; index < this._LODLevels.length; index++) {
  27488. if (this._LODLevels[index].mesh === mesh) {
  27489. this._LODLevels.splice(index, 1);
  27490. if (mesh) {
  27491. mesh._masterMesh = null;
  27492. }
  27493. }
  27494. }
  27495. this._sortLODLevels();
  27496. return this;
  27497. };
  27498. /**
  27499. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  27500. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27501. */
  27502. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  27503. if (!this._LODLevels || this._LODLevels.length === 0) {
  27504. return this;
  27505. }
  27506. var bSphere;
  27507. if (boundingSphere) {
  27508. bSphere = boundingSphere;
  27509. }
  27510. else {
  27511. var boundingInfo = this.getBoundingInfo();
  27512. bSphere = boundingInfo.boundingSphere;
  27513. }
  27514. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  27515. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  27516. if (this.onLODLevelSelection) {
  27517. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  27518. }
  27519. return this;
  27520. }
  27521. for (var index = 0; index < this._LODLevels.length; index++) {
  27522. var level = this._LODLevels[index];
  27523. if (level.distance < distanceToCamera) {
  27524. if (level.mesh) {
  27525. level.mesh._preActivate();
  27526. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  27527. }
  27528. if (this.onLODLevelSelection) {
  27529. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  27530. }
  27531. return level.mesh;
  27532. }
  27533. }
  27534. if (this.onLODLevelSelection) {
  27535. this.onLODLevelSelection(distanceToCamera, this, this);
  27536. }
  27537. return this;
  27538. };
  27539. Object.defineProperty(Mesh.prototype, "geometry", {
  27540. /**
  27541. * Returns the mesh internal Geometry object.
  27542. */
  27543. get: function () {
  27544. return this._geometry;
  27545. },
  27546. enumerable: true,
  27547. configurable: true
  27548. });
  27549. /**
  27550. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  27551. */
  27552. Mesh.prototype.getTotalVertices = function () {
  27553. if (this._geometry === null || this._geometry === undefined) {
  27554. return 0;
  27555. }
  27556. return this._geometry.getTotalVertices();
  27557. };
  27558. /**
  27559. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  27560. * 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.
  27561. * You can force the copy with forceCopy === true
  27562. * Returns null if the mesh has no geometry or no vertex buffer.
  27563. * Possible `kind` values :
  27564. * - BABYLON.VertexBuffer.PositionKind
  27565. * - BABYLON.VertexBuffer.UVKind
  27566. * - BABYLON.VertexBuffer.UV2Kind
  27567. * - BABYLON.VertexBuffer.UV3Kind
  27568. * - BABYLON.VertexBuffer.UV4Kind
  27569. * - BABYLON.VertexBuffer.UV5Kind
  27570. * - BABYLON.VertexBuffer.UV6Kind
  27571. * - BABYLON.VertexBuffer.ColorKind
  27572. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27573. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27574. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27575. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27576. */
  27577. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27578. if (!this._geometry) {
  27579. return null;
  27580. }
  27581. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  27582. };
  27583. /**
  27584. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  27585. * Returns `null` if the mesh has no geometry.
  27586. * Possible `kind` values :
  27587. * - BABYLON.VertexBuffer.PositionKind
  27588. * - BABYLON.VertexBuffer.UVKind
  27589. * - BABYLON.VertexBuffer.UV2Kind
  27590. * - BABYLON.VertexBuffer.UV3Kind
  27591. * - BABYLON.VertexBuffer.UV4Kind
  27592. * - BABYLON.VertexBuffer.UV5Kind
  27593. * - BABYLON.VertexBuffer.UV6Kind
  27594. * - BABYLON.VertexBuffer.ColorKind
  27595. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27596. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27597. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27598. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27599. */
  27600. Mesh.prototype.getVertexBuffer = function (kind) {
  27601. if (!this._geometry) {
  27602. return null;
  27603. }
  27604. return this._geometry.getVertexBuffer(kind);
  27605. };
  27606. /**
  27607. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  27608. * Possible `kind` values :
  27609. * - BABYLON.VertexBuffer.PositionKind
  27610. * - BABYLON.VertexBuffer.UVKind
  27611. * - BABYLON.VertexBuffer.UV2Kind
  27612. * - BABYLON.VertexBuffer.UV3Kind
  27613. * - BABYLON.VertexBuffer.UV4Kind
  27614. * - BABYLON.VertexBuffer.UV5Kind
  27615. * - BABYLON.VertexBuffer.UV6Kind
  27616. * - BABYLON.VertexBuffer.ColorKind
  27617. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27618. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27619. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27620. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27621. */
  27622. Mesh.prototype.isVerticesDataPresent = function (kind) {
  27623. if (!this._geometry) {
  27624. if (this._delayInfo) {
  27625. return this._delayInfo.indexOf(kind) !== -1;
  27626. }
  27627. return false;
  27628. }
  27629. return this._geometry.isVerticesDataPresent(kind);
  27630. };
  27631. /**
  27632. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  27633. * Possible `kind` values :
  27634. * - BABYLON.VertexBuffer.PositionKind
  27635. * - BABYLON.VertexBuffer.UVKind
  27636. * - BABYLON.VertexBuffer.UV2Kind
  27637. * - BABYLON.VertexBuffer.UV3Kind
  27638. * - BABYLON.VertexBuffer.UV4Kind
  27639. * - BABYLON.VertexBuffer.UV5Kind
  27640. * - BABYLON.VertexBuffer.UV6Kind
  27641. * - BABYLON.VertexBuffer.ColorKind
  27642. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27643. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27644. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27645. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27646. */
  27647. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  27648. if (!this._geometry) {
  27649. if (this._delayInfo) {
  27650. return this._delayInfo.indexOf(kind) !== -1;
  27651. }
  27652. return false;
  27653. }
  27654. return this._geometry.isVertexBufferUpdatable(kind);
  27655. };
  27656. /**
  27657. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  27658. * Possible `kind` values :
  27659. * - BABYLON.VertexBuffer.PositionKind
  27660. * - BABYLON.VertexBuffer.UVKind
  27661. * - BABYLON.VertexBuffer.UV2Kind
  27662. * - BABYLON.VertexBuffer.UV3Kind
  27663. * - BABYLON.VertexBuffer.UV4Kind
  27664. * - BABYLON.VertexBuffer.UV5Kind
  27665. * - BABYLON.VertexBuffer.UV6Kind
  27666. * - BABYLON.VertexBuffer.ColorKind
  27667. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27668. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27669. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27670. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27671. */
  27672. Mesh.prototype.getVerticesDataKinds = function () {
  27673. if (!this._geometry) {
  27674. var result = new Array();
  27675. if (this._delayInfo) {
  27676. this._delayInfo.forEach(function (kind, index, array) {
  27677. result.push(kind);
  27678. });
  27679. }
  27680. return result;
  27681. }
  27682. return this._geometry.getVerticesDataKinds();
  27683. };
  27684. /**
  27685. * Returns a positive integer : the total number of indices in this mesh geometry.
  27686. * Returns zero if the mesh has no geometry.
  27687. */
  27688. Mesh.prototype.getTotalIndices = function () {
  27689. if (!this._geometry) {
  27690. return 0;
  27691. }
  27692. return this._geometry.getTotalIndices();
  27693. };
  27694. /**
  27695. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  27696. * 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.
  27697. * Returns an empty array if the mesh has no geometry.
  27698. */
  27699. Mesh.prototype.getIndices = function (copyWhenShared) {
  27700. if (!this._geometry) {
  27701. return [];
  27702. }
  27703. return this._geometry.getIndices(copyWhenShared);
  27704. };
  27705. Object.defineProperty(Mesh.prototype, "isBlocked", {
  27706. get: function () {
  27707. return this._masterMesh !== null && this._masterMesh !== undefined;
  27708. },
  27709. enumerable: true,
  27710. configurable: true
  27711. });
  27712. /**
  27713. * Determine if the current mesh is ready to be rendered
  27714. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  27715. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  27716. * @returns true if all associated assets are ready (material, textures, shaders)
  27717. */
  27718. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  27719. if (completeCheck === void 0) { completeCheck = false; }
  27720. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  27721. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27722. return false;
  27723. }
  27724. if (!_super.prototype.isReady.call(this, completeCheck)) {
  27725. return false;
  27726. }
  27727. if (!this.subMeshes || this.subMeshes.length === 0) {
  27728. return true;
  27729. }
  27730. if (!completeCheck) {
  27731. return true;
  27732. }
  27733. var engine = this.getEngine();
  27734. var scene = this.getScene();
  27735. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  27736. this.computeWorldMatrix();
  27737. var mat = this.material || scene.defaultMaterial;
  27738. if (mat) {
  27739. if (mat.storeEffectOnSubMeshes) {
  27740. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27741. var subMesh = _a[_i];
  27742. var effectiveMaterial = subMesh.getMaterial();
  27743. if (effectiveMaterial) {
  27744. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27745. return false;
  27746. }
  27747. }
  27748. }
  27749. }
  27750. else {
  27751. if (!mat.isReady(this, hardwareInstancedRendering)) {
  27752. return false;
  27753. }
  27754. }
  27755. }
  27756. // Shadows
  27757. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  27758. var light = _c[_b];
  27759. var generator = light.getShadowGenerator();
  27760. if (generator) {
  27761. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  27762. var subMesh = _e[_d];
  27763. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  27764. return false;
  27765. }
  27766. }
  27767. }
  27768. }
  27769. // LOD
  27770. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  27771. var lod = _g[_f];
  27772. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  27773. return false;
  27774. }
  27775. }
  27776. return true;
  27777. };
  27778. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  27779. /**
  27780. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  27781. * This property is pertinent only for updatable parametric shapes.
  27782. */
  27783. get: function () {
  27784. return this._areNormalsFrozen;
  27785. },
  27786. enumerable: true,
  27787. configurable: true
  27788. });
  27789. /**
  27790. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27791. * It has no effect at all on other shapes.
  27792. * It prevents the mesh normals from being recomputed on next `positions` array update.
  27793. * Returns the Mesh.
  27794. */
  27795. Mesh.prototype.freezeNormals = function () {
  27796. this._areNormalsFrozen = true;
  27797. return this;
  27798. };
  27799. /**
  27800. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27801. * It has no effect at all on other shapes.
  27802. * It reactivates the mesh normals computation if it was previously frozen.
  27803. * Returns the Mesh.
  27804. */
  27805. Mesh.prototype.unfreezeNormals = function () {
  27806. this._areNormalsFrozen = false;
  27807. return this;
  27808. };
  27809. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  27810. /**
  27811. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  27812. */
  27813. set: function (count) {
  27814. this._overridenInstanceCount = count;
  27815. },
  27816. enumerable: true,
  27817. configurable: true
  27818. });
  27819. // Methods
  27820. Mesh.prototype._preActivate = function () {
  27821. var sceneRenderId = this.getScene().getRenderId();
  27822. if (this._preActivateId === sceneRenderId) {
  27823. return this;
  27824. }
  27825. this._preActivateId = sceneRenderId;
  27826. this._visibleInstances = null;
  27827. return this;
  27828. };
  27829. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  27830. if (this._visibleInstances) {
  27831. this._visibleInstances.intermediateDefaultRenderId = renderId;
  27832. }
  27833. return this;
  27834. };
  27835. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  27836. if (!this._visibleInstances) {
  27837. this._visibleInstances = {};
  27838. this._visibleInstances.defaultRenderId = renderId;
  27839. this._visibleInstances.selfDefaultRenderId = this._renderId;
  27840. }
  27841. if (!this._visibleInstances[renderId]) {
  27842. this._visibleInstances[renderId] = new Array();
  27843. }
  27844. this._visibleInstances[renderId].push(instance);
  27845. return this;
  27846. };
  27847. /**
  27848. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  27849. * This means the mesh underlying bounding box and sphere are recomputed.
  27850. * Returns the Mesh.
  27851. */
  27852. Mesh.prototype.refreshBoundingInfo = function () {
  27853. return this._refreshBoundingInfo(false);
  27854. };
  27855. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  27856. if (this._boundingInfo && this._boundingInfo.isLocked) {
  27857. return this;
  27858. }
  27859. var data = this._getPositionData(applySkeleton);
  27860. if (data) {
  27861. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  27862. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27863. }
  27864. if (this.subMeshes) {
  27865. for (var index = 0; index < this.subMeshes.length; index++) {
  27866. this.subMeshes[index].refreshBoundingInfo();
  27867. }
  27868. }
  27869. this._updateBoundingInfo();
  27870. return this;
  27871. };
  27872. Mesh.prototype._getPositionData = function (applySkeleton) {
  27873. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27874. if (data && applySkeleton && this.skeleton) {
  27875. data = BABYLON.Tools.Slice(data);
  27876. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27877. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27878. if (matricesWeightsData && matricesIndicesData) {
  27879. var needExtras = this.numBoneInfluencers > 4;
  27880. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27881. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27882. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  27883. var tempVector = BABYLON.Tmp.Vector3[0];
  27884. var finalMatrix = BABYLON.Tmp.Matrix[0];
  27885. var tempMatrix = BABYLON.Tmp.Matrix[1];
  27886. var matWeightIdx = 0;
  27887. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  27888. finalMatrix.reset();
  27889. var inf;
  27890. var weight;
  27891. for (inf = 0; inf < 4; inf++) {
  27892. weight = matricesWeightsData[matWeightIdx + inf];
  27893. if (weight <= 0)
  27894. break;
  27895. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  27896. finalMatrix.addToSelf(tempMatrix);
  27897. }
  27898. if (needExtras) {
  27899. for (inf = 0; inf < 4; inf++) {
  27900. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27901. if (weight <= 0)
  27902. break;
  27903. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  27904. finalMatrix.addToSelf(tempMatrix);
  27905. }
  27906. }
  27907. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  27908. tempVector.toArray(data, index);
  27909. }
  27910. }
  27911. }
  27912. return data;
  27913. };
  27914. Mesh.prototype._createGlobalSubMesh = function (force) {
  27915. var totalVertices = this.getTotalVertices();
  27916. if (!totalVertices || !this.getIndices()) {
  27917. return null;
  27918. }
  27919. // Check if we need to recreate the submeshes
  27920. if (this.subMeshes && this.subMeshes.length > 0) {
  27921. var ib = this.getIndices();
  27922. if (!ib) {
  27923. return null;
  27924. }
  27925. var totalIndices = ib.length;
  27926. var needToRecreate = false;
  27927. if (force) {
  27928. needToRecreate = true;
  27929. }
  27930. else {
  27931. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27932. var submesh = _a[_i];
  27933. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  27934. needToRecreate = true;
  27935. break;
  27936. }
  27937. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  27938. needToRecreate = true;
  27939. break;
  27940. }
  27941. }
  27942. }
  27943. if (!needToRecreate) {
  27944. return this.subMeshes[0];
  27945. }
  27946. }
  27947. this.releaseSubMeshes();
  27948. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  27949. };
  27950. Mesh.prototype.subdivide = function (count) {
  27951. if (count < 1) {
  27952. return;
  27953. }
  27954. var totalIndices = this.getTotalIndices();
  27955. var subdivisionSize = (totalIndices / count) | 0;
  27956. var offset = 0;
  27957. // Ensure that subdivisionSize is a multiple of 3
  27958. while (subdivisionSize % 3 !== 0) {
  27959. subdivisionSize++;
  27960. }
  27961. this.releaseSubMeshes();
  27962. for (var index = 0; index < count; index++) {
  27963. if (offset >= totalIndices) {
  27964. break;
  27965. }
  27966. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  27967. offset += subdivisionSize;
  27968. }
  27969. this.synchronizeInstances();
  27970. };
  27971. /**
  27972. * Sets the vertex data of the mesh geometry for the requested `kind`.
  27973. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  27974. * The `data` are either a numeric array either a Float32Array.
  27975. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  27976. * 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).
  27977. * Note that a new underlying VertexBuffer object is created each call.
  27978. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  27979. *
  27980. * Possible `kind` values :
  27981. * - BABYLON.VertexBuffer.PositionKind
  27982. * - BABYLON.VertexBuffer.UVKind
  27983. * - BABYLON.VertexBuffer.UV2Kind
  27984. * - BABYLON.VertexBuffer.UV3Kind
  27985. * - BABYLON.VertexBuffer.UV4Kind
  27986. * - BABYLON.VertexBuffer.UV5Kind
  27987. * - BABYLON.VertexBuffer.UV6Kind
  27988. * - BABYLON.VertexBuffer.ColorKind
  27989. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27990. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27991. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27992. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27993. *
  27994. * Returns the Mesh.
  27995. */
  27996. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27997. if (updatable === void 0) { updatable = false; }
  27998. if (!this._geometry) {
  27999. var vertexData = new BABYLON.VertexData();
  28000. vertexData.set(data, kind);
  28001. var scene = this.getScene();
  28002. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28003. }
  28004. else {
  28005. this._geometry.setVerticesData(kind, data, updatable, stride);
  28006. }
  28007. return this;
  28008. };
  28009. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28010. if (updatable === void 0) { updatable = true; }
  28011. var vb = this.getVertexBuffer(kind);
  28012. if (!vb || vb.isUpdatable() === updatable) {
  28013. return;
  28014. }
  28015. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28016. };
  28017. /**
  28018. * Sets the mesh VertexBuffer.
  28019. * Returns the Mesh.
  28020. */
  28021. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28022. if (!this._geometry) {
  28023. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28024. }
  28025. this._geometry.setVerticesBuffer(buffer);
  28026. return this;
  28027. };
  28028. /**
  28029. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28030. * If the mesh has no geometry, it is simply returned as it is.
  28031. * The `data` are either a numeric array either a Float32Array.
  28032. * No new underlying VertexBuffer object is created.
  28033. * 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.
  28034. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28035. *
  28036. * Possible `kind` values :
  28037. * - BABYLON.VertexBuffer.PositionKind
  28038. * - BABYLON.VertexBuffer.UVKind
  28039. * - BABYLON.VertexBuffer.UV2Kind
  28040. * - BABYLON.VertexBuffer.UV3Kind
  28041. * - BABYLON.VertexBuffer.UV4Kind
  28042. * - BABYLON.VertexBuffer.UV5Kind
  28043. * - BABYLON.VertexBuffer.UV6Kind
  28044. * - BABYLON.VertexBuffer.ColorKind
  28045. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28046. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28047. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28048. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28049. *
  28050. * Returns the Mesh.
  28051. */
  28052. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28053. if (!this._geometry) {
  28054. return this;
  28055. }
  28056. if (!makeItUnique) {
  28057. this._geometry.updateVerticesData(kind, data, updateExtends);
  28058. }
  28059. else {
  28060. this.makeGeometryUnique();
  28061. this.updateVerticesData(kind, data, updateExtends, false);
  28062. }
  28063. return this;
  28064. };
  28065. /**
  28066. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28067. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28068. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28069. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28070. * Returns the Mesh.
  28071. */
  28072. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28073. if (computeNormals === void 0) { computeNormals = true; }
  28074. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28075. if (!positions) {
  28076. return this;
  28077. }
  28078. positionFunction(positions);
  28079. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28080. if (computeNormals) {
  28081. var indices = this.getIndices();
  28082. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28083. if (!normals) {
  28084. return this;
  28085. }
  28086. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28087. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28088. }
  28089. return this;
  28090. };
  28091. /**
  28092. * Creates a un-shared specific occurence of the geometry for the mesh.
  28093. * Returns the Mesh.
  28094. */
  28095. Mesh.prototype.makeGeometryUnique = function () {
  28096. if (!this._geometry) {
  28097. return this;
  28098. }
  28099. var oldGeometry = this._geometry;
  28100. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28101. oldGeometry.releaseForMesh(this, true);
  28102. geometry.applyToMesh(this);
  28103. return this;
  28104. };
  28105. /**
  28106. * Sets the mesh indices.
  28107. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28108. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28109. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28110. * This method creates a new index buffer each call.
  28111. * Returns the Mesh.
  28112. */
  28113. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28114. if (totalVertices === void 0) { totalVertices = null; }
  28115. if (updatable === void 0) { updatable = false; }
  28116. if (!this._geometry) {
  28117. var vertexData = new BABYLON.VertexData();
  28118. vertexData.indices = indices;
  28119. var scene = this.getScene();
  28120. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28121. }
  28122. else {
  28123. this._geometry.setIndices(indices, totalVertices, updatable);
  28124. }
  28125. return this;
  28126. };
  28127. /**
  28128. * Update the current index buffer
  28129. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28130. * Returns the Mesh.
  28131. */
  28132. Mesh.prototype.updateIndices = function (indices, offset) {
  28133. if (!this._geometry) {
  28134. return this;
  28135. }
  28136. this._geometry.updateIndices(indices, offset);
  28137. return this;
  28138. };
  28139. /**
  28140. * Invert the geometry to move from a right handed system to a left handed one.
  28141. * Returns the Mesh.
  28142. */
  28143. Mesh.prototype.toLeftHanded = function () {
  28144. if (!this._geometry) {
  28145. return this;
  28146. }
  28147. this._geometry.toLeftHanded();
  28148. return this;
  28149. };
  28150. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28151. if (!this._geometry) {
  28152. return this;
  28153. }
  28154. var engine = this.getScene().getEngine();
  28155. // Wireframe
  28156. var indexToBind;
  28157. if (this._unIndexed) {
  28158. indexToBind = null;
  28159. }
  28160. else {
  28161. switch (fillMode) {
  28162. case BABYLON.Material.PointFillMode:
  28163. indexToBind = null;
  28164. break;
  28165. case BABYLON.Material.WireFrameFillMode:
  28166. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28167. break;
  28168. default:
  28169. case BABYLON.Material.TriangleFillMode:
  28170. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28171. break;
  28172. }
  28173. }
  28174. // VBOs
  28175. this._geometry._bind(effect, indexToBind);
  28176. return this;
  28177. };
  28178. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28179. if (alternate === void 0) { alternate = false; }
  28180. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28181. return this;
  28182. }
  28183. this.onBeforeDrawObservable.notifyObservers(this);
  28184. var scene = this.getScene();
  28185. var engine = scene.getEngine();
  28186. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28187. // or triangles as points
  28188. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28189. }
  28190. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28191. // Triangles as wireframe
  28192. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28193. }
  28194. else {
  28195. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28196. }
  28197. if (scene._isAlternateRenderingEnabled && !alternate) {
  28198. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28199. if (!effect || !scene.activeCamera) {
  28200. return this;
  28201. }
  28202. scene._switchToAlternateCameraConfiguration(true);
  28203. this._effectiveMaterial.bindView(effect);
  28204. this._effectiveMaterial.bindViewProjection(effect);
  28205. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28206. this._draw(subMesh, fillMode, instancesCount, true);
  28207. engine.setViewport(scene.activeCamera.viewport);
  28208. scene._switchToAlternateCameraConfiguration(false);
  28209. this._effectiveMaterial.bindView(effect);
  28210. this._effectiveMaterial.bindViewProjection(effect);
  28211. }
  28212. return this;
  28213. };
  28214. /**
  28215. * Registers for this mesh a javascript function called just before the rendering process.
  28216. * This function is passed the current mesh.
  28217. * Return the Mesh.
  28218. */
  28219. Mesh.prototype.registerBeforeRender = function (func) {
  28220. this.onBeforeRenderObservable.add(func);
  28221. return this;
  28222. };
  28223. /**
  28224. * Disposes a previously registered javascript function called before the rendering.
  28225. * This function is passed the current mesh.
  28226. * Returns the Mesh.
  28227. */
  28228. Mesh.prototype.unregisterBeforeRender = function (func) {
  28229. this.onBeforeRenderObservable.removeCallback(func);
  28230. return this;
  28231. };
  28232. /**
  28233. * Registers for this mesh a javascript function called just after the rendering is complete.
  28234. * This function is passed the current mesh.
  28235. * Returns the Mesh.
  28236. */
  28237. Mesh.prototype.registerAfterRender = function (func) {
  28238. this.onAfterRenderObservable.add(func);
  28239. return this;
  28240. };
  28241. /**
  28242. * Disposes a previously registered javascript function called after the rendering.
  28243. * This function is passed the current mesh.
  28244. * Return the Mesh.
  28245. */
  28246. Mesh.prototype.unregisterAfterRender = function (func) {
  28247. this.onAfterRenderObservable.removeCallback(func);
  28248. return this;
  28249. };
  28250. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28251. var scene = this.getScene();
  28252. this._batchCache.mustReturn = false;
  28253. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28254. this._batchCache.visibleInstances[subMeshId] = null;
  28255. if (this._visibleInstances) {
  28256. var currentRenderId = scene.getRenderId();
  28257. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28258. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28259. var selfRenderId = this._renderId;
  28260. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28261. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28262. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28263. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28264. }
  28265. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28266. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28267. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28268. this._batchCache.mustReturn = true;
  28269. return this._batchCache;
  28270. }
  28271. if (currentRenderId !== selfRenderId) {
  28272. this._batchCache.renderSelf[subMeshId] = false;
  28273. }
  28274. }
  28275. this._renderIdForInstances[subMeshId] = currentRenderId;
  28276. }
  28277. return this._batchCache;
  28278. };
  28279. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28280. var visibleInstances = batch.visibleInstances[subMesh._id];
  28281. if (!visibleInstances) {
  28282. return this;
  28283. }
  28284. var matricesCount = visibleInstances.length + 1;
  28285. var bufferSize = matricesCount * 16 * 4;
  28286. var currentInstancesBufferSize = this._instancesBufferSize;
  28287. var instancesBuffer = this._instancesBuffer;
  28288. while (this._instancesBufferSize < bufferSize) {
  28289. this._instancesBufferSize *= 2;
  28290. }
  28291. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28292. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28293. }
  28294. var offset = 0;
  28295. var instancesCount = 0;
  28296. var world = this.getWorldMatrix();
  28297. if (batch.renderSelf[subMesh._id]) {
  28298. world.copyToArray(this._instancesData, offset);
  28299. offset += 16;
  28300. instancesCount++;
  28301. }
  28302. if (visibleInstances) {
  28303. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28304. var instance = visibleInstances[instanceIndex];
  28305. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28306. offset += 16;
  28307. instancesCount++;
  28308. }
  28309. }
  28310. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28311. if (instancesBuffer) {
  28312. instancesBuffer.dispose();
  28313. }
  28314. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28315. this._instancesBuffer = instancesBuffer;
  28316. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28317. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28318. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28319. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28320. }
  28321. else {
  28322. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28323. }
  28324. this._bind(subMesh, effect, fillMode);
  28325. this._draw(subMesh, fillMode, instancesCount);
  28326. engine.unbindInstanceAttributes();
  28327. return this;
  28328. };
  28329. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28330. var scene = this.getScene();
  28331. var engine = scene.getEngine();
  28332. if (hardwareInstancedRendering) {
  28333. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28334. }
  28335. else {
  28336. if (batch.renderSelf[subMesh._id]) {
  28337. // Draw
  28338. if (onBeforeDraw) {
  28339. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28340. }
  28341. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28342. }
  28343. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28344. if (visibleInstancesForSubMesh) {
  28345. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28346. var instance = visibleInstancesForSubMesh[instanceIndex];
  28347. // World
  28348. var world = instance.getWorldMatrix();
  28349. if (onBeforeDraw) {
  28350. onBeforeDraw(true, world, effectiveMaterial);
  28351. }
  28352. // Draw
  28353. this._draw(subMesh, fillMode);
  28354. }
  28355. }
  28356. }
  28357. return this;
  28358. };
  28359. /**
  28360. * Triggers the draw call for the mesh.
  28361. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28362. * Returns the Mesh.
  28363. */
  28364. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28365. this.checkOcclusionQuery();
  28366. if (this._isOccluded) {
  28367. return this;
  28368. }
  28369. var scene = this.getScene();
  28370. // Managing instances
  28371. var batch = this._getInstancesRenderList(subMesh._id);
  28372. if (batch.mustReturn) {
  28373. return this;
  28374. }
  28375. // Checking geometry state
  28376. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28377. return this;
  28378. }
  28379. this.onBeforeRenderObservable.notifyObservers(this);
  28380. var engine = scene.getEngine();
  28381. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28382. // Material
  28383. var material = subMesh.getMaterial();
  28384. if (!material) {
  28385. return this;
  28386. }
  28387. this._effectiveMaterial = material;
  28388. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28389. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28390. return this;
  28391. }
  28392. }
  28393. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28394. return this;
  28395. }
  28396. // Alpha mode
  28397. if (enableAlphaMode) {
  28398. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28399. }
  28400. // Outline - step 1
  28401. var savedDepthWrite = engine.getDepthWrite();
  28402. if (this.renderOutline) {
  28403. engine.setDepthWrite(false);
  28404. scene.getOutlineRenderer().render(subMesh, batch);
  28405. engine.setDepthWrite(savedDepthWrite);
  28406. }
  28407. var effect;
  28408. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28409. effect = subMesh.effect;
  28410. }
  28411. else {
  28412. effect = this._effectiveMaterial.getEffect();
  28413. }
  28414. if (!effect) {
  28415. return this;
  28416. }
  28417. var sideOrientation = this.overrideMaterialSideOrientation;
  28418. if (sideOrientation == null) {
  28419. sideOrientation = this._effectiveMaterial.sideOrientation;
  28420. if (this._getWorldMatrixDeterminant() < 0) {
  28421. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  28422. }
  28423. }
  28424. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  28425. if (this._effectiveMaterial.forceDepthWrite) {
  28426. engine.setDepthWrite(true);
  28427. }
  28428. // Bind
  28429. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  28430. if (!hardwareInstancedRendering) {
  28431. this._bind(subMesh, effect, fillMode);
  28432. }
  28433. var world = this.getWorldMatrix();
  28434. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28435. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  28436. }
  28437. else {
  28438. this._effectiveMaterial.bind(world, this);
  28439. }
  28440. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  28441. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  28442. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28443. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  28444. }
  28445. // Draw
  28446. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28447. // Unbind
  28448. this._effectiveMaterial.unbind();
  28449. // Outline - step 2
  28450. if (this.renderOutline && savedDepthWrite) {
  28451. engine.setDepthWrite(true);
  28452. engine.setColorWrite(false);
  28453. scene.getOutlineRenderer().render(subMesh, batch);
  28454. engine.setColorWrite(true);
  28455. }
  28456. // Overlay
  28457. if (this.renderOverlay) {
  28458. var currentMode = engine.getAlphaMode();
  28459. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28460. scene.getOutlineRenderer().render(subMesh, batch, true);
  28461. engine.setAlphaMode(currentMode);
  28462. }
  28463. this.onAfterRenderObservable.notifyObservers(this);
  28464. return this;
  28465. };
  28466. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  28467. if (isInstance && effectiveMaterial) {
  28468. effectiveMaterial.bindOnlyWorldMatrix(world);
  28469. }
  28470. };
  28471. /**
  28472. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  28473. */
  28474. Mesh.prototype.getEmittedParticleSystems = function () {
  28475. var results = new Array();
  28476. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28477. var particleSystem = this.getScene().particleSystems[index];
  28478. if (particleSystem.emitter === this) {
  28479. results.push(particleSystem);
  28480. }
  28481. }
  28482. return results;
  28483. };
  28484. /**
  28485. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  28486. */
  28487. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  28488. var results = new Array();
  28489. var descendants = this.getDescendants();
  28490. descendants.push(this);
  28491. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28492. var particleSystem = this.getScene().particleSystems[index];
  28493. var emitter = particleSystem.emitter;
  28494. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  28495. results.push(particleSystem);
  28496. }
  28497. }
  28498. return results;
  28499. };
  28500. Mesh.prototype._checkDelayState = function () {
  28501. var scene = this.getScene();
  28502. if (this._geometry) {
  28503. this._geometry.load(scene);
  28504. }
  28505. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  28506. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28507. this._queueLoad(scene);
  28508. }
  28509. return this;
  28510. };
  28511. Mesh.prototype._queueLoad = function (scene) {
  28512. var _this = this;
  28513. scene._addPendingData(this);
  28514. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  28515. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28516. if (data instanceof ArrayBuffer) {
  28517. _this._delayLoadingFunction(data, _this);
  28518. }
  28519. else {
  28520. _this._delayLoadingFunction(JSON.parse(data), _this);
  28521. }
  28522. _this.instances.forEach(function (instance) {
  28523. instance._syncSubMeshes();
  28524. });
  28525. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28526. scene._removePendingData(_this);
  28527. }, function () { }, scene.database, getBinaryData);
  28528. return this;
  28529. };
  28530. /**
  28531. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  28532. */
  28533. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  28534. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28535. return false;
  28536. }
  28537. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  28538. return false;
  28539. }
  28540. this._checkDelayState();
  28541. return true;
  28542. };
  28543. /**
  28544. * Sets the mesh material by the material or multiMaterial `id` property.
  28545. * The material `id` is a string identifying the material or the multiMaterial.
  28546. * This method returns the Mesh.
  28547. */
  28548. Mesh.prototype.setMaterialByID = function (id) {
  28549. var materials = this.getScene().materials;
  28550. var index;
  28551. for (index = materials.length - 1; index > -1; index--) {
  28552. if (materials[index].id === id) {
  28553. this.material = materials[index];
  28554. return this;
  28555. }
  28556. }
  28557. // Multi
  28558. var multiMaterials = this.getScene().multiMaterials;
  28559. for (index = multiMaterials.length - 1; index > -1; index--) {
  28560. if (multiMaterials[index].id === id) {
  28561. this.material = multiMaterials[index];
  28562. return this;
  28563. }
  28564. }
  28565. return this;
  28566. };
  28567. /**
  28568. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  28569. */
  28570. Mesh.prototype.getAnimatables = function () {
  28571. var results = new Array();
  28572. if (this.material) {
  28573. results.push(this.material);
  28574. }
  28575. if (this.skeleton) {
  28576. results.push(this.skeleton);
  28577. }
  28578. return results;
  28579. };
  28580. /**
  28581. * Modifies the mesh geometry according to the passed transformation matrix.
  28582. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  28583. * The mesh normals are modified accordingly the same transformation.
  28584. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  28585. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28586. * Returns the Mesh.
  28587. */
  28588. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  28589. // Position
  28590. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28591. return this;
  28592. }
  28593. var submeshes = this.subMeshes.splice(0);
  28594. this._resetPointsArrayCache();
  28595. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28596. var temp = new Array();
  28597. var index;
  28598. for (index = 0; index < data.length; index += 3) {
  28599. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  28600. }
  28601. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  28602. // Normals
  28603. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28604. return this;
  28605. }
  28606. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28607. temp = [];
  28608. for (index = 0; index < data.length; index += 3) {
  28609. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  28610. }
  28611. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  28612. // flip faces?
  28613. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  28614. this.flipFaces();
  28615. }
  28616. // Restore submeshes
  28617. this.releaseSubMeshes();
  28618. this.subMeshes = submeshes;
  28619. return this;
  28620. };
  28621. /**
  28622. * Modifies the mesh geometry according to its own current World Matrix.
  28623. * The mesh World Matrix is then reset.
  28624. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  28625. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  28626. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28627. * Returns the Mesh.
  28628. */
  28629. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  28630. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  28631. this.scaling.copyFromFloats(1, 1, 1);
  28632. this.position.copyFromFloats(0, 0, 0);
  28633. this.rotation.copyFromFloats(0, 0, 0);
  28634. //only if quaternion is already set
  28635. if (this.rotationQuaternion) {
  28636. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  28637. }
  28638. this._worldMatrix = BABYLON.Matrix.Identity();
  28639. return this;
  28640. };
  28641. Object.defineProperty(Mesh.prototype, "_positions", {
  28642. // Cache
  28643. get: function () {
  28644. if (this._geometry) {
  28645. return this._geometry._positions;
  28646. }
  28647. return null;
  28648. },
  28649. enumerable: true,
  28650. configurable: true
  28651. });
  28652. Mesh.prototype._resetPointsArrayCache = function () {
  28653. if (this._geometry) {
  28654. this._geometry._resetPointsArrayCache();
  28655. }
  28656. return this;
  28657. };
  28658. Mesh.prototype._generatePointsArray = function () {
  28659. if (this._geometry) {
  28660. return this._geometry._generatePointsArray();
  28661. }
  28662. return false;
  28663. };
  28664. /**
  28665. * Returns a new Mesh object generated from the current mesh properties.
  28666. * This method must not get confused with createInstance().
  28667. * The parameter `name` is a string, the name given to the new mesh.
  28668. * The optional parameter `newParent` can be any Node object (default `null`).
  28669. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  28670. * 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.
  28671. */
  28672. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  28673. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  28674. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  28675. };
  28676. /**
  28677. * Disposes the Mesh.
  28678. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  28679. * Returns nothing.
  28680. */
  28681. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  28682. var _this = this;
  28683. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  28684. this.morphTargetManager = null;
  28685. if (this._geometry) {
  28686. this._geometry.releaseForMesh(this, true);
  28687. }
  28688. // Sources
  28689. var meshes = this.getScene().meshes;
  28690. meshes.forEach(function (abstractMesh) {
  28691. var mesh = abstractMesh;
  28692. if (mesh._source && mesh._source === _this) {
  28693. mesh._source = null;
  28694. }
  28695. });
  28696. this._source = null;
  28697. // Instances
  28698. if (this._instancesBuffer) {
  28699. this._instancesBuffer.dispose();
  28700. this._instancesBuffer = null;
  28701. }
  28702. while (this.instances.length) {
  28703. this.instances[0].dispose();
  28704. }
  28705. // Effect layers.
  28706. var effectLayers = this.getScene().effectLayers;
  28707. for (var i = 0; i < effectLayers.length; i++) {
  28708. var effectLayer = effectLayers[i];
  28709. if (effectLayer) {
  28710. effectLayer._disposeMesh(this);
  28711. }
  28712. }
  28713. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  28714. };
  28715. /**
  28716. * Modifies the mesh geometry according to a displacement map.
  28717. * 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.
  28718. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28719. * This method returns nothing.
  28720. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  28721. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28722. * 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.
  28723. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28724. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28725. *
  28726. * Returns the Mesh.
  28727. */
  28728. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  28729. var _this = this;
  28730. var scene = this.getScene();
  28731. var onload = function (img) {
  28732. // Getting height map data
  28733. var canvas = document.createElement("canvas");
  28734. var context = canvas.getContext("2d");
  28735. var heightMapWidth = img.width;
  28736. var heightMapHeight = img.height;
  28737. canvas.width = heightMapWidth;
  28738. canvas.height = heightMapHeight;
  28739. context.drawImage(img, 0, 0);
  28740. // Create VertexData from map data
  28741. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  28742. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  28743. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  28744. //execute success callback, if set
  28745. if (onSuccess) {
  28746. onSuccess(_this);
  28747. }
  28748. };
  28749. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  28750. return this;
  28751. };
  28752. /**
  28753. * Modifies the mesh geometry according to a displacementMap buffer.
  28754. * 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.
  28755. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28756. * This method returns nothing.
  28757. * 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.
  28758. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  28759. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28760. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28761. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28762. *
  28763. * Returns the Mesh.
  28764. */
  28765. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  28766. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  28767. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  28768. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28769. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  28770. return this;
  28771. }
  28772. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28773. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28774. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28775. var position = BABYLON.Vector3.Zero();
  28776. var normal = BABYLON.Vector3.Zero();
  28777. var uv = BABYLON.Vector2.Zero();
  28778. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  28779. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  28780. for (var index = 0; index < positions.length; index += 3) {
  28781. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  28782. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  28783. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  28784. // Compute height
  28785. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  28786. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  28787. var pos = (u + v * heightMapWidth) * 4;
  28788. var r = buffer[pos] / 255.0;
  28789. var g = buffer[pos + 1] / 255.0;
  28790. var b = buffer[pos + 2] / 255.0;
  28791. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28792. normal.normalize();
  28793. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  28794. position = position.add(normal);
  28795. position.toArray(positions, index);
  28796. }
  28797. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  28798. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  28799. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  28800. return this;
  28801. };
  28802. /**
  28803. * Modify the mesh to get a flat shading rendering.
  28804. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  28805. * This method returns the Mesh.
  28806. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  28807. */
  28808. Mesh.prototype.convertToFlatShadedMesh = function () {
  28809. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  28810. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28811. var kinds = this.getVerticesDataKinds();
  28812. var vbs = {};
  28813. var data = {};
  28814. var newdata = {};
  28815. var updatableNormals = false;
  28816. var kindIndex;
  28817. var kind;
  28818. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28819. kind = kinds[kindIndex];
  28820. var vertexBuffer = this.getVertexBuffer(kind);
  28821. if (kind === BABYLON.VertexBuffer.NormalKind) {
  28822. updatableNormals = vertexBuffer.isUpdatable();
  28823. kinds.splice(kindIndex, 1);
  28824. kindIndex--;
  28825. continue;
  28826. }
  28827. vbs[kind] = vertexBuffer;
  28828. data[kind] = vbs[kind].getData();
  28829. newdata[kind] = [];
  28830. }
  28831. // Save previous submeshes
  28832. var previousSubmeshes = this.subMeshes.slice(0);
  28833. var indices = this.getIndices();
  28834. var totalIndices = this.getTotalIndices();
  28835. // Generating unique vertices per face
  28836. var index;
  28837. for (index = 0; index < totalIndices; index++) {
  28838. var vertexIndex = indices[index];
  28839. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28840. kind = kinds[kindIndex];
  28841. var stride = vbs[kind].getStrideSize();
  28842. for (var offset = 0; offset < stride; offset++) {
  28843. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28844. }
  28845. }
  28846. }
  28847. // Updating faces & normal
  28848. var normals = [];
  28849. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  28850. for (index = 0; index < totalIndices; index += 3) {
  28851. indices[index] = index;
  28852. indices[index + 1] = index + 1;
  28853. indices[index + 2] = index + 2;
  28854. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  28855. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  28856. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  28857. var p1p2 = p1.subtract(p2);
  28858. var p3p2 = p3.subtract(p2);
  28859. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  28860. // Store same normals for every vertex
  28861. for (var localIndex = 0; localIndex < 3; localIndex++) {
  28862. normals.push(normal.x);
  28863. normals.push(normal.y);
  28864. normals.push(normal.z);
  28865. }
  28866. }
  28867. this.setIndices(indices);
  28868. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  28869. // Updating vertex buffers
  28870. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28871. kind = kinds[kindIndex];
  28872. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28873. }
  28874. // Updating submeshes
  28875. this.releaseSubMeshes();
  28876. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28877. var previousOne = previousSubmeshes[submeshIndex];
  28878. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28879. }
  28880. this.synchronizeInstances();
  28881. return this;
  28882. };
  28883. /**
  28884. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  28885. * In other words, more vertices, no more indices and a single bigger VBO.
  28886. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  28887. * Returns the Mesh.
  28888. */
  28889. Mesh.prototype.convertToUnIndexedMesh = function () {
  28890. /// <summary>Remove indices by unfolding faces into buffers</summary>
  28891. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28892. var kinds = this.getVerticesDataKinds();
  28893. var vbs = {};
  28894. var data = {};
  28895. var newdata = {};
  28896. var kindIndex;
  28897. var kind;
  28898. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28899. kind = kinds[kindIndex];
  28900. var vertexBuffer = this.getVertexBuffer(kind);
  28901. vbs[kind] = vertexBuffer;
  28902. data[kind] = vbs[kind].getData();
  28903. newdata[kind] = [];
  28904. }
  28905. // Save previous submeshes
  28906. var previousSubmeshes = this.subMeshes.slice(0);
  28907. var indices = this.getIndices();
  28908. var totalIndices = this.getTotalIndices();
  28909. // Generating unique vertices per face
  28910. var index;
  28911. for (index = 0; index < totalIndices; index++) {
  28912. var vertexIndex = indices[index];
  28913. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28914. kind = kinds[kindIndex];
  28915. var stride = vbs[kind].getStrideSize();
  28916. for (var offset = 0; offset < stride; offset++) {
  28917. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28918. }
  28919. }
  28920. }
  28921. // Updating indices
  28922. for (index = 0; index < totalIndices; index += 3) {
  28923. indices[index] = index;
  28924. indices[index + 1] = index + 1;
  28925. indices[index + 2] = index + 2;
  28926. }
  28927. this.setIndices(indices);
  28928. // Updating vertex buffers
  28929. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28930. kind = kinds[kindIndex];
  28931. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28932. }
  28933. // Updating submeshes
  28934. this.releaseSubMeshes();
  28935. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28936. var previousOne = previousSubmeshes[submeshIndex];
  28937. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28938. }
  28939. this._unIndexed = true;
  28940. this.synchronizeInstances();
  28941. return this;
  28942. };
  28943. /**
  28944. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  28945. * This method returns the Mesh.
  28946. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  28947. */
  28948. Mesh.prototype.flipFaces = function (flipNormals) {
  28949. if (flipNormals === void 0) { flipNormals = false; }
  28950. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  28951. var i;
  28952. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  28953. for (i = 0; i < vertex_data.normals.length; i++) {
  28954. vertex_data.normals[i] *= -1;
  28955. }
  28956. }
  28957. if (vertex_data.indices) {
  28958. var temp;
  28959. for (i = 0; i < vertex_data.indices.length; i += 3) {
  28960. // reassign indices
  28961. temp = vertex_data.indices[i + 1];
  28962. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  28963. vertex_data.indices[i + 2] = temp;
  28964. }
  28965. }
  28966. vertex_data.applyToMesh(this);
  28967. return this;
  28968. };
  28969. // Instances
  28970. /**
  28971. * Creates a new InstancedMesh object from the mesh model.
  28972. * An instance shares the same properties and the same material than its model.
  28973. * Only these properties of each instance can then be set individually :
  28974. * - position
  28975. * - rotation
  28976. * - rotationQuaternion
  28977. * - setPivotMatrix
  28978. * - scaling
  28979. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  28980. * Warning : this method is not supported for Line mesh and LineSystem
  28981. */
  28982. Mesh.prototype.createInstance = function (name) {
  28983. return new BABYLON.InstancedMesh(name, this);
  28984. };
  28985. /**
  28986. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  28987. * After this call, all the mesh instances have the same submeshes than the current mesh.
  28988. * This method returns the Mesh.
  28989. */
  28990. Mesh.prototype.synchronizeInstances = function () {
  28991. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  28992. var instance = this.instances[instanceIndex];
  28993. instance._syncSubMeshes();
  28994. }
  28995. return this;
  28996. };
  28997. /**
  28998. * Simplify the mesh according to the given array of settings.
  28999. * Function will return immediately and will simplify async. It returns the Mesh.
  29000. * @param settings a collection of simplification settings.
  29001. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29002. * @param type the type of simplification to run.
  29003. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29004. */
  29005. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29006. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29007. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29008. this.getScene().simplificationQueue.addTask({
  29009. settings: settings,
  29010. parallelProcessing: parallelProcessing,
  29011. mesh: this,
  29012. simplificationType: simplificationType,
  29013. successCallback: successCallback
  29014. });
  29015. return this;
  29016. };
  29017. /**
  29018. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29019. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29020. * This should be used together with the simplification to avoid disappearing triangles.
  29021. * Returns the Mesh.
  29022. * @param successCallback an optional success callback to be called after the optimization finished.
  29023. */
  29024. Mesh.prototype.optimizeIndices = function (successCallback) {
  29025. var _this = this;
  29026. var indices = this.getIndices();
  29027. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29028. if (!positions || !indices) {
  29029. return this;
  29030. }
  29031. var vectorPositions = new Array();
  29032. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29033. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29034. }
  29035. var dupes = new Array();
  29036. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29037. var realPos = vectorPositions.length - 1 - iteration;
  29038. var testedPosition = vectorPositions[realPos];
  29039. for (var j = 0; j < realPos; ++j) {
  29040. var againstPosition = vectorPositions[j];
  29041. if (testedPosition.equals(againstPosition)) {
  29042. dupes[realPos] = j;
  29043. break;
  29044. }
  29045. }
  29046. }, function () {
  29047. for (var i = 0; i < indices.length; ++i) {
  29048. indices[i] = dupes[indices[i]] || indices[i];
  29049. }
  29050. //indices are now reordered
  29051. var originalSubMeshes = _this.subMeshes.slice(0);
  29052. _this.setIndices(indices);
  29053. _this.subMeshes = originalSubMeshes;
  29054. if (successCallback) {
  29055. successCallback(_this);
  29056. }
  29057. });
  29058. return this;
  29059. };
  29060. Mesh.prototype.serialize = function (serializationObject) {
  29061. serializationObject.name = this.name;
  29062. serializationObject.id = this.id;
  29063. serializationObject.type = this.getClassName();
  29064. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29065. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29066. }
  29067. serializationObject.position = this.position.asArray();
  29068. if (this.rotationQuaternion) {
  29069. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29070. }
  29071. else if (this.rotation) {
  29072. serializationObject.rotation = this.rotation.asArray();
  29073. }
  29074. serializationObject.scaling = this.scaling.asArray();
  29075. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29076. serializationObject.isEnabled = this.isEnabled(false);
  29077. serializationObject.isVisible = this.isVisible;
  29078. serializationObject.infiniteDistance = this.infiniteDistance;
  29079. serializationObject.pickable = this.isPickable;
  29080. serializationObject.receiveShadows = this.receiveShadows;
  29081. serializationObject.billboardMode = this.billboardMode;
  29082. serializationObject.visibility = this.visibility;
  29083. serializationObject.checkCollisions = this.checkCollisions;
  29084. serializationObject.isBlocker = this.isBlocker;
  29085. // Parent
  29086. if (this.parent) {
  29087. serializationObject.parentId = this.parent.id;
  29088. }
  29089. // Geometry
  29090. serializationObject.isUnIndexed = this.isUnIndexed;
  29091. var geometry = this._geometry;
  29092. if (geometry) {
  29093. var geometryId = geometry.id;
  29094. serializationObject.geometryId = geometryId;
  29095. // SubMeshes
  29096. serializationObject.subMeshes = [];
  29097. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29098. var subMesh = this.subMeshes[subIndex];
  29099. serializationObject.subMeshes.push({
  29100. materialIndex: subMesh.materialIndex,
  29101. verticesStart: subMesh.verticesStart,
  29102. verticesCount: subMesh.verticesCount,
  29103. indexStart: subMesh.indexStart,
  29104. indexCount: subMesh.indexCount
  29105. });
  29106. }
  29107. }
  29108. // Material
  29109. if (this.material) {
  29110. serializationObject.materialId = this.material.id;
  29111. }
  29112. else {
  29113. this.material = null;
  29114. }
  29115. // Morph targets
  29116. if (this.morphTargetManager) {
  29117. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29118. }
  29119. // Skeleton
  29120. if (this.skeleton) {
  29121. serializationObject.skeletonId = this.skeleton.id;
  29122. }
  29123. // Physics
  29124. //TODO implement correct serialization for physics impostors.
  29125. var impostor = this.getPhysicsImpostor();
  29126. if (impostor) {
  29127. serializationObject.physicsMass = impostor.getParam("mass");
  29128. serializationObject.physicsFriction = impostor.getParam("friction");
  29129. serializationObject.physicsRestitution = impostor.getParam("mass");
  29130. serializationObject.physicsImpostor = impostor.type;
  29131. }
  29132. // Metadata
  29133. if (this.metadata) {
  29134. serializationObject.metadata = this.metadata;
  29135. }
  29136. // Instances
  29137. serializationObject.instances = [];
  29138. for (var index = 0; index < this.instances.length; index++) {
  29139. var instance = this.instances[index];
  29140. var serializationInstance = {
  29141. name: instance.name,
  29142. id: instance.id,
  29143. position: instance.position.asArray(),
  29144. scaling: instance.scaling.asArray()
  29145. };
  29146. if (instance.rotationQuaternion) {
  29147. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29148. }
  29149. else if (instance.rotation) {
  29150. serializationInstance.rotation = instance.rotation.asArray();
  29151. }
  29152. serializationObject.instances.push(serializationInstance);
  29153. // Animations
  29154. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29155. serializationInstance.ranges = instance.serializeAnimationRanges();
  29156. }
  29157. //
  29158. // Animations
  29159. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29160. serializationObject.ranges = this.serializeAnimationRanges();
  29161. // Layer mask
  29162. serializationObject.layerMask = this.layerMask;
  29163. // Alpha
  29164. serializationObject.alphaIndex = this.alphaIndex;
  29165. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29166. // Overlay
  29167. serializationObject.overlayAlpha = this.overlayAlpha;
  29168. serializationObject.overlayColor = this.overlayColor.asArray();
  29169. serializationObject.renderOverlay = this.renderOverlay;
  29170. // Fog
  29171. serializationObject.applyFog = this.applyFog;
  29172. // Action Manager
  29173. if (this.actionManager) {
  29174. serializationObject.actions = this.actionManager.serialize(this.name);
  29175. }
  29176. };
  29177. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29178. if (!this.geometry) {
  29179. return;
  29180. }
  29181. this._markSubMeshesAsAttributesDirty();
  29182. var morphTargetManager = this._morphTargetManager;
  29183. if (morphTargetManager && morphTargetManager.vertexCount) {
  29184. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29185. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29186. this.morphTargetManager = null;
  29187. return;
  29188. }
  29189. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29190. var morphTarget = morphTargetManager.getActiveTarget(index);
  29191. var positions = morphTarget.getPositions();
  29192. if (!positions) {
  29193. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29194. return;
  29195. }
  29196. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29197. var normals = morphTarget.getNormals();
  29198. if (normals) {
  29199. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29200. }
  29201. var tangents = morphTarget.getTangents();
  29202. if (tangents) {
  29203. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29204. }
  29205. }
  29206. }
  29207. else {
  29208. var index = 0;
  29209. // Positions
  29210. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29211. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29212. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29213. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29214. }
  29215. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29216. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29217. }
  29218. index++;
  29219. }
  29220. }
  29221. };
  29222. // Statics
  29223. /**
  29224. * Returns a new Mesh object parsed from the source provided.
  29225. * The parameter `parsedMesh` is the source.
  29226. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29227. */
  29228. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29229. var mesh;
  29230. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29231. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29232. }
  29233. else {
  29234. mesh = new Mesh(parsedMesh.name, scene);
  29235. }
  29236. mesh.id = parsedMesh.id;
  29237. if (BABYLON.Tags) {
  29238. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29239. }
  29240. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29241. if (parsedMesh.metadata !== undefined) {
  29242. mesh.metadata = parsedMesh.metadata;
  29243. }
  29244. if (parsedMesh.rotationQuaternion) {
  29245. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29246. }
  29247. else if (parsedMesh.rotation) {
  29248. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29249. }
  29250. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29251. if (parsedMesh.localMatrix) {
  29252. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29253. }
  29254. else if (parsedMesh.pivotMatrix) {
  29255. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29256. }
  29257. mesh.setEnabled(parsedMesh.isEnabled);
  29258. mesh.isVisible = parsedMesh.isVisible;
  29259. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29260. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29261. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29262. if (parsedMesh.applyFog !== undefined) {
  29263. mesh.applyFog = parsedMesh.applyFog;
  29264. }
  29265. if (parsedMesh.pickable !== undefined) {
  29266. mesh.isPickable = parsedMesh.pickable;
  29267. }
  29268. if (parsedMesh.alphaIndex !== undefined) {
  29269. mesh.alphaIndex = parsedMesh.alphaIndex;
  29270. }
  29271. mesh.receiveShadows = parsedMesh.receiveShadows;
  29272. mesh.billboardMode = parsedMesh.billboardMode;
  29273. if (parsedMesh.visibility !== undefined) {
  29274. mesh.visibility = parsedMesh.visibility;
  29275. }
  29276. mesh.checkCollisions = parsedMesh.checkCollisions;
  29277. if (parsedMesh.isBlocker !== undefined) {
  29278. mesh.isBlocker = parsedMesh.isBlocker;
  29279. }
  29280. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29281. // freezeWorldMatrix
  29282. if (parsedMesh.freezeWorldMatrix) {
  29283. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29284. }
  29285. // Parent
  29286. if (parsedMesh.parentId) {
  29287. mesh._waitingParentId = parsedMesh.parentId;
  29288. }
  29289. // Actions
  29290. if (parsedMesh.actions !== undefined) {
  29291. mesh._waitingActions = parsedMesh.actions;
  29292. }
  29293. // Overlay
  29294. if (parsedMesh.overlayAlpha !== undefined) {
  29295. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29296. }
  29297. if (parsedMesh.overlayColor !== undefined) {
  29298. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29299. }
  29300. if (parsedMesh.renderOverlay !== undefined) {
  29301. mesh.renderOverlay = parsedMesh.renderOverlay;
  29302. }
  29303. // Geometry
  29304. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29305. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29306. if (parsedMesh.delayLoadingFile) {
  29307. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29308. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29309. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29310. if (parsedMesh._binaryInfo) {
  29311. mesh._binaryInfo = parsedMesh._binaryInfo;
  29312. }
  29313. mesh._delayInfo = [];
  29314. if (parsedMesh.hasUVs) {
  29315. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29316. }
  29317. if (parsedMesh.hasUVs2) {
  29318. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29319. }
  29320. if (parsedMesh.hasUVs3) {
  29321. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29322. }
  29323. if (parsedMesh.hasUVs4) {
  29324. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29325. }
  29326. if (parsedMesh.hasUVs5) {
  29327. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29328. }
  29329. if (parsedMesh.hasUVs6) {
  29330. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29331. }
  29332. if (parsedMesh.hasColors) {
  29333. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29334. }
  29335. if (parsedMesh.hasMatricesIndices) {
  29336. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29337. }
  29338. if (parsedMesh.hasMatricesWeights) {
  29339. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29340. }
  29341. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29342. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29343. mesh._checkDelayState();
  29344. }
  29345. }
  29346. else {
  29347. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29348. }
  29349. // Material
  29350. if (parsedMesh.materialId) {
  29351. mesh.setMaterialByID(parsedMesh.materialId);
  29352. }
  29353. else {
  29354. mesh.material = null;
  29355. }
  29356. // Morph targets
  29357. if (parsedMesh.morphTargetManagerId > -1) {
  29358. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29359. }
  29360. // Skeleton
  29361. if (parsedMesh.skeletonId > -1) {
  29362. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29363. if (parsedMesh.numBoneInfluencers) {
  29364. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29365. }
  29366. }
  29367. // Animations
  29368. if (parsedMesh.animations) {
  29369. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29370. var parsedAnimation = parsedMesh.animations[animationIndex];
  29371. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29372. }
  29373. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29374. }
  29375. if (parsedMesh.autoAnimate) {
  29376. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29377. }
  29378. // Layer Mask
  29379. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29380. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29381. }
  29382. else {
  29383. mesh.layerMask = 0x0FFFFFFF;
  29384. }
  29385. // Physics
  29386. if (parsedMesh.physicsImpostor) {
  29387. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29388. mass: parsedMesh.physicsMass,
  29389. friction: parsedMesh.physicsFriction,
  29390. restitution: parsedMesh.physicsRestitution
  29391. }, scene);
  29392. }
  29393. // Instances
  29394. if (parsedMesh.instances) {
  29395. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29396. var parsedInstance = parsedMesh.instances[index];
  29397. var instance = mesh.createInstance(parsedInstance.name);
  29398. if (parsedInstance.id) {
  29399. instance.id = parsedInstance.id;
  29400. }
  29401. if (BABYLON.Tags) {
  29402. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  29403. }
  29404. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  29405. if (parsedInstance.parentId) {
  29406. instance._waitingParentId = parsedInstance.parentId;
  29407. }
  29408. if (parsedInstance.rotationQuaternion) {
  29409. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  29410. }
  29411. else if (parsedInstance.rotation) {
  29412. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  29413. }
  29414. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  29415. instance.checkCollisions = mesh.checkCollisions;
  29416. if (parsedMesh.animations) {
  29417. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29418. parsedAnimation = parsedMesh.animations[animationIndex];
  29419. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29420. }
  29421. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  29422. }
  29423. }
  29424. }
  29425. return mesh;
  29426. };
  29427. /**
  29428. * Creates a ribbon mesh.
  29429. * Please consider using the same method from the MeshBuilder class instead.
  29430. * 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.
  29431. *
  29432. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  29433. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  29434. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  29435. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  29436. * 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.
  29437. * 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.
  29438. * 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
  29439. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29440. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29441. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29442. */
  29443. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  29444. if (closeArray === void 0) { closeArray = false; }
  29445. if (updatable === void 0) { updatable = false; }
  29446. return BABYLON.MeshBuilder.CreateRibbon(name, {
  29447. pathArray: pathArray,
  29448. closeArray: closeArray,
  29449. closePath: closePath,
  29450. offset: offset,
  29451. updatable: updatable,
  29452. sideOrientation: sideOrientation,
  29453. instance: instance
  29454. }, scene);
  29455. };
  29456. /**
  29457. * Creates a plane polygonal mesh. By default, this is a disc.
  29458. * Please consider using the same method from the MeshBuilder class instead.
  29459. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  29460. * 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.
  29461. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29462. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29463. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29464. */
  29465. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  29466. if (scene === void 0) { scene = null; }
  29467. var options = {
  29468. radius: radius,
  29469. tessellation: tessellation,
  29470. sideOrientation: sideOrientation,
  29471. updatable: updatable
  29472. };
  29473. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  29474. };
  29475. /**
  29476. * Creates a box mesh.
  29477. * Please consider using the same method from the MeshBuilder class instead.
  29478. * The parameter `size` sets the size (float) of each box side (default 1).
  29479. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29480. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29481. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29482. */
  29483. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  29484. if (scene === void 0) { scene = null; }
  29485. var options = {
  29486. size: size,
  29487. sideOrientation: sideOrientation,
  29488. updatable: updatable
  29489. };
  29490. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  29491. };
  29492. /**
  29493. * Creates a sphere mesh.
  29494. * Please consider using the same method from the MeshBuilder class instead.
  29495. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  29496. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  29497. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29498. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29499. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29500. */
  29501. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  29502. var options = {
  29503. segments: segments,
  29504. diameterX: diameter,
  29505. diameterY: diameter,
  29506. diameterZ: diameter,
  29507. sideOrientation: sideOrientation,
  29508. updatable: updatable
  29509. };
  29510. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  29511. };
  29512. /**
  29513. * Creates a cylinder or a cone mesh.
  29514. * Please consider using the same method from the MeshBuilder class instead.
  29515. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  29516. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  29517. * 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.
  29518. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  29519. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  29520. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29521. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29522. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29523. */
  29524. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  29525. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  29526. if (scene !== undefined) {
  29527. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  29528. updatable = scene;
  29529. }
  29530. scene = subdivisions;
  29531. subdivisions = 1;
  29532. }
  29533. var options = {
  29534. height: height,
  29535. diameterTop: diameterTop,
  29536. diameterBottom: diameterBottom,
  29537. tessellation: tessellation,
  29538. subdivisions: subdivisions,
  29539. sideOrientation: sideOrientation,
  29540. updatable: updatable
  29541. };
  29542. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  29543. };
  29544. // Torus (Code from SharpDX.org)
  29545. /**
  29546. * Creates a torus mesh.
  29547. * Please consider using the same method from the MeshBuilder class instead.
  29548. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  29549. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  29550. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  29551. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29552. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29553. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29554. */
  29555. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  29556. var options = {
  29557. diameter: diameter,
  29558. thickness: thickness,
  29559. tessellation: tessellation,
  29560. sideOrientation: sideOrientation,
  29561. updatable: updatable
  29562. };
  29563. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  29564. };
  29565. /**
  29566. * Creates a torus knot mesh.
  29567. * Please consider using the same method from the MeshBuilder class instead.
  29568. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  29569. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  29570. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  29571. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  29572. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29573. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29574. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29575. */
  29576. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  29577. var options = {
  29578. radius: radius,
  29579. tube: tube,
  29580. radialSegments: radialSegments,
  29581. tubularSegments: tubularSegments,
  29582. p: p,
  29583. q: q,
  29584. sideOrientation: sideOrientation,
  29585. updatable: updatable
  29586. };
  29587. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  29588. };
  29589. /**
  29590. * Creates a line mesh.
  29591. * Please consider using the same method from the MeshBuilder class instead.
  29592. * 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.
  29593. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29594. * The parameter `points` is an array successive Vector3.
  29595. * 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
  29596. * When updating an instance, remember that only point positions can change, not the number of points.
  29597. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29598. */
  29599. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  29600. if (scene === void 0) { scene = null; }
  29601. if (updatable === void 0) { updatable = false; }
  29602. if (instance === void 0) { instance = null; }
  29603. var options = {
  29604. points: points,
  29605. updatable: updatable,
  29606. instance: instance
  29607. };
  29608. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  29609. };
  29610. /**
  29611. * Creates a dashed line mesh.
  29612. * Please consider using the same method from the MeshBuilder class instead.
  29613. * 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.
  29614. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29615. * The parameter `points` is an array successive Vector3.
  29616. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  29617. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  29618. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  29619. * 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
  29620. * When updating an instance, remember that only point positions can change, not the number of points.
  29621. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29622. */
  29623. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  29624. if (scene === void 0) { scene = null; }
  29625. var options = {
  29626. points: points,
  29627. dashSize: dashSize,
  29628. gapSize: gapSize,
  29629. dashNb: dashNb,
  29630. updatable: updatable,
  29631. instance: instance
  29632. };
  29633. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  29634. };
  29635. /**
  29636. * Creates a polygon mesh.
  29637. * Please consider using the same method from the MeshBuilder class instead.
  29638. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29639. * 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.
  29640. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29641. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29642. * Remember you can only change the shape positions, not their number when updating a polygon.
  29643. */
  29644. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  29645. var options = {
  29646. shape: shape,
  29647. holes: holes,
  29648. updatable: updatable,
  29649. sideOrientation: sideOrientation
  29650. };
  29651. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  29652. };
  29653. /**
  29654. * Creates an extruded polygon mesh, with depth in the Y direction.
  29655. * Please consider using the same method from the MeshBuilder class instead.
  29656. */
  29657. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  29658. var options = {
  29659. shape: shape,
  29660. holes: holes,
  29661. depth: depth,
  29662. updatable: updatable,
  29663. sideOrientation: sideOrientation
  29664. };
  29665. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  29666. };
  29667. /**
  29668. * Creates an extruded shape mesh.
  29669. * 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.
  29670. * Please consider using the same method from the MeshBuilder class instead.
  29671. *
  29672. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29673. * 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
  29674. * extruded along the Z axis.
  29675. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29676. * 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.
  29677. * The parameter `scale` (float, default 1) is the value to scale the shape.
  29678. * 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
  29679. * 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
  29680. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29681. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29682. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29683. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29684. */
  29685. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  29686. if (scene === void 0) { scene = null; }
  29687. var options = {
  29688. shape: shape,
  29689. path: path,
  29690. scale: scale,
  29691. rotation: rotation,
  29692. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29693. sideOrientation: sideOrientation,
  29694. instance: instance,
  29695. updatable: updatable
  29696. };
  29697. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  29698. };
  29699. /**
  29700. * Creates an custom extruded shape mesh.
  29701. * 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.
  29702. * Please consider using the same method from the MeshBuilder class instead.
  29703. *
  29704. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29705. * 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
  29706. * extruded along the Z axis.
  29707. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29708. * 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
  29709. * and the distance of this point from the begining of the path :
  29710. * ```javascript
  29711. * var rotationFunction = function(i, distance) {
  29712. * // do things
  29713. * return rotationValue; }
  29714. * ```
  29715. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  29716. * 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
  29717. * and the distance of this point from the begining of the path :
  29718. * ```javascript
  29719. * var scaleFunction = function(i, distance) {
  29720. * // do things
  29721. * return scaleValue;}
  29722. * ```
  29723. * It must returns a float value that will be the scale value applied to the shape on each path point.
  29724. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  29725. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  29726. * 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
  29727. * 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
  29728. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29729. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29730. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29731. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29732. */
  29733. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  29734. var options = {
  29735. shape: shape,
  29736. path: path,
  29737. scaleFunction: scaleFunction,
  29738. rotationFunction: rotationFunction,
  29739. ribbonCloseArray: ribbonCloseArray,
  29740. ribbonClosePath: ribbonClosePath,
  29741. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29742. sideOrientation: sideOrientation,
  29743. instance: instance,
  29744. updatable: updatable
  29745. };
  29746. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  29747. };
  29748. /**
  29749. * Creates lathe mesh.
  29750. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  29751. * Please consider using the same method from the MeshBuilder class instead.
  29752. * 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
  29753. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  29754. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  29755. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  29756. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29757. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29758. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29759. */
  29760. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  29761. var options = {
  29762. shape: shape,
  29763. radius: radius,
  29764. tessellation: tessellation,
  29765. sideOrientation: sideOrientation,
  29766. updatable: updatable
  29767. };
  29768. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  29769. };
  29770. /**
  29771. * Creates a plane mesh.
  29772. * Please consider using the same method from the MeshBuilder class instead.
  29773. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  29774. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29775. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29776. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29777. */
  29778. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  29779. var options = {
  29780. size: size,
  29781. width: size,
  29782. height: size,
  29783. sideOrientation: sideOrientation,
  29784. updatable: updatable
  29785. };
  29786. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  29787. };
  29788. /**
  29789. * Creates a ground mesh.
  29790. * Please consider using the same method from the MeshBuilder class instead.
  29791. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  29792. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  29793. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29794. */
  29795. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  29796. var options = {
  29797. width: width,
  29798. height: height,
  29799. subdivisions: subdivisions,
  29800. updatable: updatable
  29801. };
  29802. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  29803. };
  29804. /**
  29805. * Creates a tiled ground mesh.
  29806. * Please consider using the same method from the MeshBuilder class instead.
  29807. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  29808. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  29809. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  29810. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  29811. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  29812. * numbers of subdivisions on the ground width and height of each tile.
  29813. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29814. */
  29815. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  29816. var options = {
  29817. xmin: xmin,
  29818. zmin: zmin,
  29819. xmax: xmax,
  29820. zmax: zmax,
  29821. subdivisions: subdivisions,
  29822. precision: precision,
  29823. updatable: updatable
  29824. };
  29825. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  29826. };
  29827. /**
  29828. * Creates a ground mesh from a height map.
  29829. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  29830. * Please consider using the same method from the MeshBuilder class instead.
  29831. * The parameter `url` sets the URL of the height map image resource.
  29832. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  29833. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  29834. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  29835. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  29836. * 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).
  29837. * This function is passed the newly built mesh :
  29838. * ```javascript
  29839. * function(mesh) { // do things
  29840. * return; }
  29841. * ```
  29842. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29843. */
  29844. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  29845. var options = {
  29846. width: width,
  29847. height: height,
  29848. subdivisions: subdivisions,
  29849. minHeight: minHeight,
  29850. maxHeight: maxHeight,
  29851. updatable: updatable,
  29852. onReady: onReady
  29853. };
  29854. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  29855. };
  29856. /**
  29857. * Creates a tube mesh.
  29858. * 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.
  29859. * Please consider using the same method from the MeshBuilder class instead.
  29860. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  29861. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  29862. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  29863. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  29864. * 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.
  29865. * It must return a radius value (positive float) :
  29866. * ```javascript
  29867. * var radiusFunction = function(i, distance) {
  29868. * // do things
  29869. * return radius; }
  29870. * ```
  29871. * 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
  29872. * 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
  29873. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29874. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29875. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29876. */
  29877. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  29878. var options = {
  29879. path: path,
  29880. radius: radius,
  29881. tessellation: tessellation,
  29882. radiusFunction: radiusFunction,
  29883. arc: 1,
  29884. cap: cap,
  29885. updatable: updatable,
  29886. sideOrientation: sideOrientation,
  29887. instance: instance
  29888. };
  29889. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  29890. };
  29891. /**
  29892. * Creates a polyhedron mesh.
  29893. * Please consider using the same method from the MeshBuilder class instead.
  29894. * 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
  29895. * to choose the wanted type.
  29896. * The parameter `size` (positive float, default 1) sets the polygon size.
  29897. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  29898. * 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`.
  29899. * 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
  29900. * 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)`).
  29901. * 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
  29902. * 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.
  29903. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29904. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29905. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29906. */
  29907. Mesh.CreatePolyhedron = function (name, options, scene) {
  29908. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  29909. };
  29910. /**
  29911. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  29912. * Please consider using the same method from the MeshBuilder class instead.
  29913. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  29914. * 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`).
  29915. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  29916. * 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.
  29917. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29918. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29919. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29920. */
  29921. Mesh.CreateIcoSphere = function (name, options, scene) {
  29922. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  29923. };
  29924. /**
  29925. * Creates a decal mesh.
  29926. * Please consider using the same method from the MeshBuilder class instead.
  29927. * 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.
  29928. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  29929. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  29930. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  29931. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  29932. */
  29933. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  29934. var options = {
  29935. position: position,
  29936. normal: normal,
  29937. size: size,
  29938. angle: angle
  29939. };
  29940. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  29941. };
  29942. // Skeletons
  29943. /**
  29944. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29945. */
  29946. Mesh.prototype.setPositionsForCPUSkinning = function () {
  29947. if (!this._sourcePositions) {
  29948. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29949. if (!source) {
  29950. return this._sourcePositions;
  29951. }
  29952. this._sourcePositions = new Float32Array(source);
  29953. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  29954. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  29955. }
  29956. }
  29957. return this._sourcePositions;
  29958. };
  29959. /**
  29960. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29961. */
  29962. Mesh.prototype.setNormalsForCPUSkinning = function () {
  29963. if (!this._sourceNormals) {
  29964. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29965. if (!source) {
  29966. return this._sourceNormals;
  29967. }
  29968. this._sourceNormals = new Float32Array(source);
  29969. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  29970. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  29971. }
  29972. }
  29973. return this._sourceNormals;
  29974. };
  29975. /**
  29976. * Updates the vertex buffer by applying transformation from the bones.
  29977. * Returns the Mesh.
  29978. *
  29979. * @param {skeleton} skeleton to apply
  29980. */
  29981. Mesh.prototype.applySkeleton = function (skeleton) {
  29982. if (!this.geometry) {
  29983. return this;
  29984. }
  29985. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  29986. return this;
  29987. }
  29988. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  29989. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29990. return this;
  29991. }
  29992. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29993. return this;
  29994. }
  29995. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29996. return this;
  29997. }
  29998. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29999. return this;
  30000. }
  30001. if (!this._sourcePositions) {
  30002. var submeshes = this.subMeshes.slice();
  30003. this.setPositionsForCPUSkinning();
  30004. this.subMeshes = submeshes;
  30005. }
  30006. if (!this._sourceNormals) {
  30007. this.setNormalsForCPUSkinning();
  30008. }
  30009. // positionsData checks for not being Float32Array will only pass at most once
  30010. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30011. if (!positionsData) {
  30012. return this;
  30013. }
  30014. if (!(positionsData instanceof Float32Array)) {
  30015. positionsData = new Float32Array(positionsData);
  30016. }
  30017. // normalsData checks for not being Float32Array will only pass at most once
  30018. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30019. if (!normalsData) {
  30020. return this;
  30021. }
  30022. if (!(normalsData instanceof Float32Array)) {
  30023. normalsData = new Float32Array(normalsData);
  30024. }
  30025. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30026. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30027. if (!matricesWeightsData || !matricesIndicesData) {
  30028. return this;
  30029. }
  30030. var needExtras = this.numBoneInfluencers > 4;
  30031. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30032. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30033. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30034. var tempVector3 = BABYLON.Vector3.Zero();
  30035. var finalMatrix = new BABYLON.Matrix();
  30036. var tempMatrix = new BABYLON.Matrix();
  30037. var matWeightIdx = 0;
  30038. var inf;
  30039. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30040. var weight;
  30041. for (inf = 0; inf < 4; inf++) {
  30042. weight = matricesWeightsData[matWeightIdx + inf];
  30043. if (weight > 0) {
  30044. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30045. finalMatrix.addToSelf(tempMatrix);
  30046. }
  30047. else
  30048. break;
  30049. }
  30050. if (needExtras) {
  30051. for (inf = 0; inf < 4; inf++) {
  30052. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30053. if (weight > 0) {
  30054. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30055. finalMatrix.addToSelf(tempMatrix);
  30056. }
  30057. else
  30058. break;
  30059. }
  30060. }
  30061. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30062. tempVector3.toArray(positionsData, index);
  30063. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30064. tempVector3.toArray(normalsData, index);
  30065. finalMatrix.reset();
  30066. }
  30067. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30068. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30069. return this;
  30070. };
  30071. // Tools
  30072. /**
  30073. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30074. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30075. */
  30076. Mesh.MinMax = function (meshes) {
  30077. var minVector = null;
  30078. var maxVector = null;
  30079. meshes.forEach(function (mesh, index, array) {
  30080. var boundingInfo = mesh.getBoundingInfo();
  30081. var boundingBox = boundingInfo.boundingBox;
  30082. if (!minVector || !maxVector) {
  30083. minVector = boundingBox.minimumWorld;
  30084. maxVector = boundingBox.maximumWorld;
  30085. }
  30086. else {
  30087. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30088. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30089. }
  30090. });
  30091. if (!minVector || !maxVector) {
  30092. return {
  30093. min: BABYLON.Vector3.Zero(),
  30094. max: BABYLON.Vector3.Zero()
  30095. };
  30096. }
  30097. return {
  30098. min: minVector,
  30099. max: maxVector
  30100. };
  30101. };
  30102. /**
  30103. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30104. */
  30105. Mesh.Center = function (meshesOrMinMaxVector) {
  30106. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30107. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30108. };
  30109. /**
  30110. * Merge the array of meshes into a single mesh for performance reasons.
  30111. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30112. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30113. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30114. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30115. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30116. */
  30117. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30118. if (disposeSource === void 0) { disposeSource = true; }
  30119. var index;
  30120. if (!allow32BitsIndices) {
  30121. var totalVertices = 0;
  30122. // Counting vertices
  30123. for (index = 0; index < meshes.length; index++) {
  30124. if (meshes[index]) {
  30125. totalVertices += meshes[index].getTotalVertices();
  30126. if (totalVertices > 65536) {
  30127. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30128. return null;
  30129. }
  30130. }
  30131. }
  30132. }
  30133. // Merge
  30134. var vertexData = null;
  30135. var otherVertexData;
  30136. var indiceArray = new Array();
  30137. var source = null;
  30138. for (index = 0; index < meshes.length; index++) {
  30139. if (meshes[index]) {
  30140. meshes[index].computeWorldMatrix(true);
  30141. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30142. otherVertexData.transform(meshes[index].getWorldMatrix());
  30143. if (vertexData) {
  30144. vertexData.merge(otherVertexData);
  30145. }
  30146. else {
  30147. vertexData = otherVertexData;
  30148. source = meshes[index];
  30149. }
  30150. if (subdivideWithSubMeshes) {
  30151. indiceArray.push(meshes[index].getTotalIndices());
  30152. }
  30153. }
  30154. }
  30155. source = source;
  30156. if (!meshSubclass) {
  30157. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30158. }
  30159. vertexData.applyToMesh(meshSubclass);
  30160. // Setting properties
  30161. meshSubclass.material = source.material;
  30162. meshSubclass.checkCollisions = source.checkCollisions;
  30163. // Cleaning
  30164. if (disposeSource) {
  30165. for (index = 0; index < meshes.length; index++) {
  30166. if (meshes[index]) {
  30167. meshes[index].dispose();
  30168. }
  30169. }
  30170. }
  30171. // Subdivide
  30172. if (subdivideWithSubMeshes) {
  30173. //-- Suppresions du submesh global
  30174. meshSubclass.releaseSubMeshes();
  30175. index = 0;
  30176. var offset = 0;
  30177. //-- aplique la subdivision en fonction du tableau d'indices
  30178. while (index < indiceArray.length) {
  30179. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30180. offset += indiceArray[index];
  30181. index++;
  30182. }
  30183. }
  30184. return meshSubclass;
  30185. };
  30186. // Consts
  30187. Mesh._FRONTSIDE = 0;
  30188. Mesh._BACKSIDE = 1;
  30189. Mesh._DOUBLESIDE = 2;
  30190. Mesh._DEFAULTSIDE = 0;
  30191. Mesh._NO_CAP = 0;
  30192. Mesh._CAP_START = 1;
  30193. Mesh._CAP_END = 2;
  30194. Mesh._CAP_ALL = 3;
  30195. return Mesh;
  30196. }(BABYLON.AbstractMesh));
  30197. BABYLON.Mesh = Mesh;
  30198. })(BABYLON || (BABYLON = {}));
  30199. //# sourceMappingURL=babylon.mesh.js.map
  30200. var BABYLON;
  30201. (function (BABYLON) {
  30202. var BaseSubMesh = /** @class */ (function () {
  30203. function BaseSubMesh() {
  30204. }
  30205. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30206. get: function () {
  30207. return this._materialEffect;
  30208. },
  30209. enumerable: true,
  30210. configurable: true
  30211. });
  30212. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30213. if (defines === void 0) { defines = null; }
  30214. if (this._materialEffect === effect) {
  30215. if (!effect) {
  30216. this._materialDefines = null;
  30217. }
  30218. return;
  30219. }
  30220. this._materialDefines = defines;
  30221. this._materialEffect = effect;
  30222. };
  30223. return BaseSubMesh;
  30224. }());
  30225. BABYLON.BaseSubMesh = BaseSubMesh;
  30226. var SubMesh = /** @class */ (function (_super) {
  30227. __extends(SubMesh, _super);
  30228. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30229. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30230. var _this = _super.call(this) || this;
  30231. _this.materialIndex = materialIndex;
  30232. _this.verticesStart = verticesStart;
  30233. _this.verticesCount = verticesCount;
  30234. _this.indexStart = indexStart;
  30235. _this.indexCount = indexCount;
  30236. _this._renderId = 0;
  30237. _this._mesh = mesh;
  30238. _this._renderingMesh = renderingMesh || mesh;
  30239. mesh.subMeshes.push(_this);
  30240. _this._trianglePlanes = [];
  30241. _this._id = mesh.subMeshes.length - 1;
  30242. if (createBoundingBox) {
  30243. _this.refreshBoundingInfo();
  30244. mesh.computeWorldMatrix(true);
  30245. }
  30246. return _this;
  30247. }
  30248. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30249. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30250. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30251. };
  30252. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30253. get: function () {
  30254. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30255. },
  30256. enumerable: true,
  30257. configurable: true
  30258. });
  30259. /**
  30260. * Returns the submesh BoudingInfo object.
  30261. */
  30262. SubMesh.prototype.getBoundingInfo = function () {
  30263. if (this.IsGlobal) {
  30264. return this._mesh.getBoundingInfo();
  30265. }
  30266. return this._boundingInfo;
  30267. };
  30268. /**
  30269. * Sets the submesh BoundingInfo.
  30270. * Return the SubMesh.
  30271. */
  30272. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30273. this._boundingInfo = boundingInfo;
  30274. return this;
  30275. };
  30276. /**
  30277. * Returns the mesh of the current submesh.
  30278. */
  30279. SubMesh.prototype.getMesh = function () {
  30280. return this._mesh;
  30281. };
  30282. /**
  30283. * Returns the rendering mesh of the submesh.
  30284. */
  30285. SubMesh.prototype.getRenderingMesh = function () {
  30286. return this._renderingMesh;
  30287. };
  30288. /**
  30289. * Returns the submesh material.
  30290. */
  30291. SubMesh.prototype.getMaterial = function () {
  30292. var rootMaterial = this._renderingMesh.material;
  30293. if (rootMaterial === null || rootMaterial === undefined) {
  30294. return this._mesh.getScene().defaultMaterial;
  30295. }
  30296. else if (rootMaterial.getSubMaterial) {
  30297. var multiMaterial = rootMaterial;
  30298. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30299. if (this._currentMaterial !== effectiveMaterial) {
  30300. this._currentMaterial = effectiveMaterial;
  30301. this._materialDefines = null;
  30302. }
  30303. return effectiveMaterial;
  30304. }
  30305. return rootMaterial;
  30306. };
  30307. // Methods
  30308. /**
  30309. * Sets a new updated BoundingInfo object to the submesh.
  30310. * Returns the SubMesh.
  30311. */
  30312. SubMesh.prototype.refreshBoundingInfo = function () {
  30313. this._lastColliderWorldVertices = null;
  30314. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30315. return this;
  30316. }
  30317. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30318. if (!data) {
  30319. this._boundingInfo = this._mesh.getBoundingInfo();
  30320. return this;
  30321. }
  30322. var indices = this._renderingMesh.getIndices();
  30323. var extend;
  30324. //is this the only submesh?
  30325. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30326. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30327. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30328. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30329. }
  30330. else {
  30331. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30332. }
  30333. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30334. return this;
  30335. };
  30336. SubMesh.prototype._checkCollision = function (collider) {
  30337. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30338. return boundingInfo._checkCollision(collider);
  30339. };
  30340. /**
  30341. * Updates the submesh BoundingInfo.
  30342. * Returns the Submesh.
  30343. */
  30344. SubMesh.prototype.updateBoundingInfo = function (world) {
  30345. var boundingInfo = this.getBoundingInfo();
  30346. if (!boundingInfo) {
  30347. this.refreshBoundingInfo();
  30348. boundingInfo = this.getBoundingInfo();
  30349. }
  30350. boundingInfo.update(world);
  30351. return this;
  30352. };
  30353. /**
  30354. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30355. * Boolean returned.
  30356. */
  30357. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30358. var boundingInfo = this.getBoundingInfo();
  30359. if (!boundingInfo) {
  30360. return false;
  30361. }
  30362. return boundingInfo.isInFrustum(frustumPlanes);
  30363. };
  30364. /**
  30365. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30366. * Boolean returned.
  30367. */
  30368. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30369. var boundingInfo = this.getBoundingInfo();
  30370. if (!boundingInfo) {
  30371. return false;
  30372. }
  30373. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30374. };
  30375. /**
  30376. * Renders the submesh.
  30377. * Returns it.
  30378. */
  30379. SubMesh.prototype.render = function (enableAlphaMode) {
  30380. this._renderingMesh.render(this, enableAlphaMode);
  30381. return this;
  30382. };
  30383. /**
  30384. * Returns a new Index Buffer.
  30385. * Type returned : WebGLBuffer.
  30386. */
  30387. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30388. if (!this._linesIndexBuffer) {
  30389. var linesIndices = [];
  30390. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30391. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30392. }
  30393. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30394. this.linesIndexCount = linesIndices.length;
  30395. }
  30396. return this._linesIndexBuffer;
  30397. };
  30398. /**
  30399. * True is the passed Ray intersects the submesh bounding box.
  30400. * Boolean returned.
  30401. */
  30402. SubMesh.prototype.canIntersects = function (ray) {
  30403. var boundingInfo = this.getBoundingInfo();
  30404. if (!boundingInfo) {
  30405. return false;
  30406. }
  30407. return ray.intersectsBox(boundingInfo.boundingBox);
  30408. };
  30409. /**
  30410. * Returns an object IntersectionInfo.
  30411. */
  30412. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  30413. var intersectInfo = null;
  30414. // LineMesh first as it's also a Mesh...
  30415. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  30416. var lineMesh = this._mesh;
  30417. // Line test
  30418. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  30419. var p0 = positions[indices[index]];
  30420. var p1 = positions[indices[index + 1]];
  30421. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  30422. if (length < 0) {
  30423. continue;
  30424. }
  30425. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  30426. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  30427. if (fastCheck) {
  30428. break;
  30429. }
  30430. }
  30431. }
  30432. }
  30433. else {
  30434. // Triangles test
  30435. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30436. var p0 = positions[indices[index]];
  30437. var p1 = positions[indices[index + 1]];
  30438. var p2 = positions[indices[index + 2]];
  30439. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  30440. if (currentIntersectInfo) {
  30441. if (currentIntersectInfo.distance < 0) {
  30442. continue;
  30443. }
  30444. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  30445. intersectInfo = currentIntersectInfo;
  30446. intersectInfo.faceId = index / 3;
  30447. if (fastCheck) {
  30448. break;
  30449. }
  30450. }
  30451. }
  30452. }
  30453. }
  30454. return intersectInfo;
  30455. };
  30456. SubMesh.prototype._rebuild = function () {
  30457. if (this._linesIndexBuffer) {
  30458. this._linesIndexBuffer = null;
  30459. }
  30460. };
  30461. // Clone
  30462. /**
  30463. * Creates a new Submesh from the passed Mesh.
  30464. */
  30465. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  30466. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  30467. if (!this.IsGlobal) {
  30468. var boundingInfo = this.getBoundingInfo();
  30469. if (!boundingInfo) {
  30470. return result;
  30471. }
  30472. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  30473. }
  30474. return result;
  30475. };
  30476. // Dispose
  30477. /**
  30478. * Disposes the Submesh.
  30479. * Returns nothing.
  30480. */
  30481. SubMesh.prototype.dispose = function () {
  30482. if (this._linesIndexBuffer) {
  30483. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  30484. this._linesIndexBuffer = null;
  30485. }
  30486. // Remove from mesh
  30487. var index = this._mesh.subMeshes.indexOf(this);
  30488. this._mesh.subMeshes.splice(index, 1);
  30489. };
  30490. // Statics
  30491. /**
  30492. * Creates a new Submesh from the passed parameters :
  30493. * - materialIndex (integer) : the index of the main mesh material.
  30494. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  30495. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  30496. * - mesh (Mesh) : the main mesh to create the submesh from.
  30497. * - renderingMesh (optional Mesh) : rendering mesh.
  30498. */
  30499. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  30500. var minVertexIndex = Number.MAX_VALUE;
  30501. var maxVertexIndex = -Number.MAX_VALUE;
  30502. renderingMesh = (renderingMesh || mesh);
  30503. var indices = renderingMesh.getIndices();
  30504. for (var index = startIndex; index < startIndex + indexCount; index++) {
  30505. var vertexIndex = indices[index];
  30506. if (vertexIndex < minVertexIndex)
  30507. minVertexIndex = vertexIndex;
  30508. if (vertexIndex > maxVertexIndex)
  30509. maxVertexIndex = vertexIndex;
  30510. }
  30511. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  30512. };
  30513. return SubMesh;
  30514. }(BaseSubMesh));
  30515. BABYLON.SubMesh = SubMesh;
  30516. })(BABYLON || (BABYLON = {}));
  30517. //# sourceMappingURL=babylon.subMesh.js.map
  30518. var __assign = (this && this.__assign) || Object.assign || function(t) {
  30519. for (var s, i = 1, n = arguments.length; i < n; i++) {
  30520. s = arguments[i];
  30521. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  30522. t[p] = s[p];
  30523. }
  30524. return t;
  30525. };
  30526. var BABYLON;
  30527. (function (BABYLON) {
  30528. /**
  30529. * Manages the defines for the Material.
  30530. */
  30531. var MaterialDefines = /** @class */ (function () {
  30532. function MaterialDefines() {
  30533. this._isDirty = true;
  30534. this._areLightsDirty = true;
  30535. this._areAttributesDirty = true;
  30536. this._areTexturesDirty = true;
  30537. this._areFresnelDirty = true;
  30538. this._areMiscDirty = true;
  30539. this._areImageProcessingDirty = true;
  30540. this._normals = false;
  30541. this._uvs = false;
  30542. this._needNormals = false;
  30543. this._needUVs = false;
  30544. }
  30545. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  30546. /**
  30547. * Specifies if the material needs to be re-calculated.
  30548. */
  30549. get: function () {
  30550. return this._isDirty;
  30551. },
  30552. enumerable: true,
  30553. configurable: true
  30554. });
  30555. /**
  30556. * Marks the material to indicate that it has been re-calculated.
  30557. */
  30558. MaterialDefines.prototype.markAsProcessed = function () {
  30559. this._isDirty = false;
  30560. this._areAttributesDirty = false;
  30561. this._areTexturesDirty = false;
  30562. this._areFresnelDirty = false;
  30563. this._areLightsDirty = false;
  30564. this._areMiscDirty = false;
  30565. this._areImageProcessingDirty = false;
  30566. };
  30567. /**
  30568. * Marks the material to indicate that it needs to be re-calculated.
  30569. */
  30570. MaterialDefines.prototype.markAsUnprocessed = function () {
  30571. this._isDirty = true;
  30572. };
  30573. /**
  30574. * Marks the material to indicate all of its defines need to be re-calculated.
  30575. */
  30576. MaterialDefines.prototype.markAllAsDirty = function () {
  30577. this._areTexturesDirty = true;
  30578. this._areAttributesDirty = true;
  30579. this._areLightsDirty = true;
  30580. this._areFresnelDirty = true;
  30581. this._areMiscDirty = true;
  30582. this._areImageProcessingDirty = true;
  30583. this._isDirty = true;
  30584. };
  30585. /**
  30586. * Marks the material to indicate that image processing needs to be re-calculated.
  30587. */
  30588. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  30589. this._areImageProcessingDirty = true;
  30590. this._isDirty = true;
  30591. };
  30592. /**
  30593. * Marks the material to indicate the lights need to be re-calculated.
  30594. */
  30595. MaterialDefines.prototype.markAsLightDirty = function () {
  30596. this._areLightsDirty = true;
  30597. this._isDirty = true;
  30598. };
  30599. /**
  30600. * Marks the attribute state as changed.
  30601. */
  30602. MaterialDefines.prototype.markAsAttributesDirty = function () {
  30603. this._areAttributesDirty = true;
  30604. this._isDirty = true;
  30605. };
  30606. /**
  30607. * Marks the texture state as changed.
  30608. */
  30609. MaterialDefines.prototype.markAsTexturesDirty = function () {
  30610. this._areTexturesDirty = true;
  30611. this._isDirty = true;
  30612. };
  30613. /**
  30614. * Marks the fresnel state as changed.
  30615. */
  30616. MaterialDefines.prototype.markAsFresnelDirty = function () {
  30617. this._areFresnelDirty = true;
  30618. this._isDirty = true;
  30619. };
  30620. /**
  30621. * Marks the misc state as changed.
  30622. */
  30623. MaterialDefines.prototype.markAsMiscDirty = function () {
  30624. this._areMiscDirty = true;
  30625. this._isDirty = true;
  30626. };
  30627. /**
  30628. * Rebuilds the material defines.
  30629. */
  30630. MaterialDefines.prototype.rebuild = function () {
  30631. if (this._keys) {
  30632. delete this._keys;
  30633. }
  30634. this._keys = [];
  30635. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  30636. var key = _a[_i];
  30637. if (key[0] === "_") {
  30638. continue;
  30639. }
  30640. this._keys.push(key);
  30641. }
  30642. };
  30643. /**
  30644. * Specifies if two material defines are equal.
  30645. * @param other - A material define instance to compare to.
  30646. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  30647. */
  30648. MaterialDefines.prototype.isEqual = function (other) {
  30649. if (this._keys.length !== other._keys.length) {
  30650. return false;
  30651. }
  30652. for (var index = 0; index < this._keys.length; index++) {
  30653. var prop = this._keys[index];
  30654. if (this[prop] !== other[prop]) {
  30655. return false;
  30656. }
  30657. }
  30658. return true;
  30659. };
  30660. /**
  30661. * Clones this instance's defines to another instance.
  30662. * @param other - material defines to clone values to.
  30663. */
  30664. MaterialDefines.prototype.cloneTo = function (other) {
  30665. if (this._keys.length !== other._keys.length) {
  30666. other._keys = this._keys.slice(0);
  30667. }
  30668. for (var index = 0; index < this._keys.length; index++) {
  30669. var prop = this._keys[index];
  30670. other[prop] = this[prop];
  30671. }
  30672. };
  30673. /**
  30674. * Resets the material define values.
  30675. */
  30676. MaterialDefines.prototype.reset = function () {
  30677. for (var index = 0; index < this._keys.length; index++) {
  30678. var prop = this._keys[index];
  30679. if (typeof (this[prop]) === "number") {
  30680. this[prop] = 0;
  30681. }
  30682. else {
  30683. this[prop] = false;
  30684. }
  30685. }
  30686. };
  30687. /**
  30688. * Converts the material define values to a string.
  30689. * @returns - String of material define information.
  30690. */
  30691. MaterialDefines.prototype.toString = function () {
  30692. var result = "";
  30693. for (var index = 0; index < this._keys.length; index++) {
  30694. var prop = this._keys[index];
  30695. var value = this[prop];
  30696. if (typeof (value) === "number") {
  30697. result += "#define " + prop + " " + this[prop] + "\n";
  30698. }
  30699. else if (value) {
  30700. result += "#define " + prop + "\n";
  30701. }
  30702. }
  30703. return result;
  30704. };
  30705. return MaterialDefines;
  30706. }());
  30707. BABYLON.MaterialDefines = MaterialDefines;
  30708. /**
  30709. * This offers the main features of a material in BJS.
  30710. */
  30711. var Material = /** @class */ (function () {
  30712. /**
  30713. * Creates a material instance.
  30714. * @param name - The name of the material.
  30715. * @param scene - The BJS scene to reference.
  30716. * @param doNotAdd - Specifies if the material should be added to the scene.
  30717. */
  30718. function Material(name, scene, doNotAdd) {
  30719. /**
  30720. * Specifies if the ready state should be checked on each call.
  30721. */
  30722. this.checkReadyOnEveryCall = false;
  30723. /**
  30724. * Specifies if the ready state should be checked once.
  30725. */
  30726. this.checkReadyOnlyOnce = false;
  30727. /**
  30728. * The state of the material.
  30729. */
  30730. this.state = "";
  30731. /**
  30732. * The alpha value of the material.
  30733. */
  30734. this._alpha = 1.0;
  30735. /**
  30736. * Specifies if back face culling is enabled.
  30737. */
  30738. this._backFaceCulling = true;
  30739. /**
  30740. * Specifies if the material should be serialized.
  30741. */
  30742. this.doNotSerialize = false;
  30743. /**
  30744. * Specifies if the effect should be stored on sub meshes.
  30745. */
  30746. this.storeEffectOnSubMeshes = false;
  30747. /**
  30748. * An event triggered when the material is disposed.
  30749. * @type {BABYLON.Observable}
  30750. */
  30751. this.onDisposeObservable = new BABYLON.Observable();
  30752. /**
  30753. * An event triggered when the material is bound.
  30754. * @type {BABYLON.Observable}
  30755. */
  30756. this.onBindObservable = new BABYLON.Observable();
  30757. /**
  30758. * An event triggered when the material is unbound.
  30759. * @type {BABYLON.Observable}
  30760. */
  30761. this.onUnBindObservable = new BABYLON.Observable();
  30762. /**
  30763. * Stores the value of the alpha mode.
  30764. */
  30765. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  30766. /**
  30767. * Stores the state of the need depth pre-pass value.
  30768. */
  30769. this._needDepthPrePass = false;
  30770. /**
  30771. * Specifies if depth writing should be disabled.
  30772. */
  30773. this.disableDepthWrite = false;
  30774. /**
  30775. * Specifies if depth writing should be forced.
  30776. */
  30777. this.forceDepthWrite = false;
  30778. /**
  30779. * Specifies if there should be a separate pass for culling.
  30780. */
  30781. this.separateCullingPass = false;
  30782. /**
  30783. * Stores the state specifing if fog should be enabled.
  30784. */
  30785. this._fogEnabled = true;
  30786. /**
  30787. * Stores the size of points.
  30788. */
  30789. this.pointSize = 1.0;
  30790. /**
  30791. * Stores the z offset value.
  30792. */
  30793. this.zOffset = 0;
  30794. /**
  30795. * Specifies if the material was previously ready.
  30796. */
  30797. this._wasPreviouslyReady = false;
  30798. /**
  30799. * Stores the fill mode state.
  30800. */
  30801. this._fillMode = Material.TriangleFillMode;
  30802. this.name = name;
  30803. this.id = name || BABYLON.Tools.RandomId();
  30804. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30805. if (this._scene.useRightHandedSystem) {
  30806. this.sideOrientation = Material.ClockWiseSideOrientation;
  30807. }
  30808. else {
  30809. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  30810. }
  30811. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  30812. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  30813. if (!doNotAdd) {
  30814. this._scene.materials.push(this);
  30815. }
  30816. }
  30817. Object.defineProperty(Material, "TriangleFillMode", {
  30818. /**
  30819. * Returns the triangle fill mode.
  30820. */
  30821. get: function () {
  30822. return Material._TriangleFillMode;
  30823. },
  30824. enumerable: true,
  30825. configurable: true
  30826. });
  30827. Object.defineProperty(Material, "WireFrameFillMode", {
  30828. /**
  30829. * Returns the wireframe mode.
  30830. */
  30831. get: function () {
  30832. return Material._WireFrameFillMode;
  30833. },
  30834. enumerable: true,
  30835. configurable: true
  30836. });
  30837. Object.defineProperty(Material, "PointFillMode", {
  30838. /**
  30839. * Returns the point fill mode.
  30840. */
  30841. get: function () {
  30842. return Material._PointFillMode;
  30843. },
  30844. enumerable: true,
  30845. configurable: true
  30846. });
  30847. Object.defineProperty(Material, "PointListDrawMode", {
  30848. /**
  30849. * Returns the point list draw mode.
  30850. */
  30851. get: function () {
  30852. return Material._PointListDrawMode;
  30853. },
  30854. enumerable: true,
  30855. configurable: true
  30856. });
  30857. Object.defineProperty(Material, "LineListDrawMode", {
  30858. /**
  30859. * Returns the line list draw mode.
  30860. */
  30861. get: function () {
  30862. return Material._LineListDrawMode;
  30863. },
  30864. enumerable: true,
  30865. configurable: true
  30866. });
  30867. Object.defineProperty(Material, "LineLoopDrawMode", {
  30868. /**
  30869. * Returns the line loop draw mode.
  30870. */
  30871. get: function () {
  30872. return Material._LineLoopDrawMode;
  30873. },
  30874. enumerable: true,
  30875. configurable: true
  30876. });
  30877. Object.defineProperty(Material, "LineStripDrawMode", {
  30878. /**
  30879. * Returns the line strip draw mode.
  30880. */
  30881. get: function () {
  30882. return Material._LineStripDrawMode;
  30883. },
  30884. enumerable: true,
  30885. configurable: true
  30886. });
  30887. Object.defineProperty(Material, "TriangleStripDrawMode", {
  30888. /**
  30889. * Returns the triangle strip draw mode.
  30890. */
  30891. get: function () {
  30892. return Material._TriangleStripDrawMode;
  30893. },
  30894. enumerable: true,
  30895. configurable: true
  30896. });
  30897. Object.defineProperty(Material, "TriangleFanDrawMode", {
  30898. /**
  30899. * Returns the triangle fan draw mode.
  30900. */
  30901. get: function () {
  30902. return Material._TriangleFanDrawMode;
  30903. },
  30904. enumerable: true,
  30905. configurable: true
  30906. });
  30907. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  30908. /**
  30909. * Returns the clock-wise side orientation.
  30910. */
  30911. get: function () {
  30912. return Material._ClockWiseSideOrientation;
  30913. },
  30914. enumerable: true,
  30915. configurable: true
  30916. });
  30917. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  30918. /**
  30919. * Returns the counter clock-wise side orientation.
  30920. */
  30921. get: function () {
  30922. return Material._CounterClockWiseSideOrientation;
  30923. },
  30924. enumerable: true,
  30925. configurable: true
  30926. });
  30927. Object.defineProperty(Material, "TextureDirtyFlag", {
  30928. /**
  30929. * Returns the dirty texture flag value.
  30930. */
  30931. get: function () {
  30932. return Material._TextureDirtyFlag;
  30933. },
  30934. enumerable: true,
  30935. configurable: true
  30936. });
  30937. Object.defineProperty(Material, "LightDirtyFlag", {
  30938. /**
  30939. * Returns the dirty light flag value.
  30940. */
  30941. get: function () {
  30942. return Material._LightDirtyFlag;
  30943. },
  30944. enumerable: true,
  30945. configurable: true
  30946. });
  30947. Object.defineProperty(Material, "FresnelDirtyFlag", {
  30948. /**
  30949. * Returns the dirty fresnel flag value.
  30950. */
  30951. get: function () {
  30952. return Material._FresnelDirtyFlag;
  30953. },
  30954. enumerable: true,
  30955. configurable: true
  30956. });
  30957. Object.defineProperty(Material, "AttributesDirtyFlag", {
  30958. /**
  30959. * Returns the dirty attributes flag value.
  30960. */
  30961. get: function () {
  30962. return Material._AttributesDirtyFlag;
  30963. },
  30964. enumerable: true,
  30965. configurable: true
  30966. });
  30967. Object.defineProperty(Material, "MiscDirtyFlag", {
  30968. /**
  30969. * Returns the dirty misc flag value.
  30970. */
  30971. get: function () {
  30972. return Material._MiscDirtyFlag;
  30973. },
  30974. enumerable: true,
  30975. configurable: true
  30976. });
  30977. Object.defineProperty(Material.prototype, "alpha", {
  30978. /**
  30979. * Gets the alpha value of the material.
  30980. */
  30981. get: function () {
  30982. return this._alpha;
  30983. },
  30984. /**
  30985. * Sets the alpha value of the material.
  30986. */
  30987. set: function (value) {
  30988. if (this._alpha === value) {
  30989. return;
  30990. }
  30991. this._alpha = value;
  30992. this.markAsDirty(Material.MiscDirtyFlag);
  30993. },
  30994. enumerable: true,
  30995. configurable: true
  30996. });
  30997. Object.defineProperty(Material.prototype, "backFaceCulling", {
  30998. /**
  30999. * Gets the back-face culling state.
  31000. */
  31001. get: function () {
  31002. return this._backFaceCulling;
  31003. },
  31004. /**
  31005. * Sets the back-face culling state.
  31006. */
  31007. set: function (value) {
  31008. if (this._backFaceCulling === value) {
  31009. return;
  31010. }
  31011. this._backFaceCulling = value;
  31012. this.markAsDirty(Material.TextureDirtyFlag);
  31013. },
  31014. enumerable: true,
  31015. configurable: true
  31016. });
  31017. Object.defineProperty(Material.prototype, "onDispose", {
  31018. /**
  31019. * Called during a dispose event.
  31020. */
  31021. set: function (callback) {
  31022. if (this._onDisposeObserver) {
  31023. this.onDisposeObservable.remove(this._onDisposeObserver);
  31024. }
  31025. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31026. },
  31027. enumerable: true,
  31028. configurable: true
  31029. });
  31030. Object.defineProperty(Material.prototype, "onBind", {
  31031. /**
  31032. * Called during a bind event.
  31033. */
  31034. set: function (callback) {
  31035. if (this._onBindObserver) {
  31036. this.onBindObservable.remove(this._onBindObserver);
  31037. }
  31038. this._onBindObserver = this.onBindObservable.add(callback);
  31039. },
  31040. enumerable: true,
  31041. configurable: true
  31042. });
  31043. Object.defineProperty(Material.prototype, "alphaMode", {
  31044. /**
  31045. * Gets the value of the alpha mode.
  31046. */
  31047. get: function () {
  31048. return this._alphaMode;
  31049. },
  31050. /**
  31051. * Sets the value of the alpha mode.
  31052. */
  31053. set: function (value) {
  31054. if (this._alphaMode === value) {
  31055. return;
  31056. }
  31057. this._alphaMode = value;
  31058. this.markAsDirty(Material.TextureDirtyFlag);
  31059. },
  31060. enumerable: true,
  31061. configurable: true
  31062. });
  31063. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31064. /**
  31065. * Gets the depth pre-pass value.
  31066. */
  31067. get: function () {
  31068. return this._needDepthPrePass;
  31069. },
  31070. /**
  31071. * Sets the need depth pre-pass value.
  31072. */
  31073. set: function (value) {
  31074. if (this._needDepthPrePass === value) {
  31075. return;
  31076. }
  31077. this._needDepthPrePass = value;
  31078. if (this._needDepthPrePass) {
  31079. this.checkReadyOnEveryCall = true;
  31080. }
  31081. },
  31082. enumerable: true,
  31083. configurable: true
  31084. });
  31085. Object.defineProperty(Material.prototype, "fogEnabled", {
  31086. /**
  31087. * Gets the value of the fog enabled state.
  31088. */
  31089. get: function () {
  31090. return this._fogEnabled;
  31091. },
  31092. /**
  31093. * Sets the state for enabling fog.
  31094. */
  31095. set: function (value) {
  31096. if (this._fogEnabled === value) {
  31097. return;
  31098. }
  31099. this._fogEnabled = value;
  31100. this.markAsDirty(Material.MiscDirtyFlag);
  31101. },
  31102. enumerable: true,
  31103. configurable: true
  31104. });
  31105. Object.defineProperty(Material.prototype, "wireframe", {
  31106. /**
  31107. * Gets a value specifying if wireframe mode is enabled.
  31108. */
  31109. get: function () {
  31110. return this._fillMode === Material.WireFrameFillMode;
  31111. },
  31112. /**
  31113. * Sets the state of wireframe mode.
  31114. */
  31115. set: function (value) {
  31116. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31117. },
  31118. enumerable: true,
  31119. configurable: true
  31120. });
  31121. Object.defineProperty(Material.prototype, "pointsCloud", {
  31122. /**
  31123. * Gets the value specifying if point clouds are enabled.
  31124. */
  31125. get: function () {
  31126. return this._fillMode === Material.PointFillMode;
  31127. },
  31128. /**
  31129. * Sets the state of point cloud mode.
  31130. */
  31131. set: function (value) {
  31132. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31133. },
  31134. enumerable: true,
  31135. configurable: true
  31136. });
  31137. Object.defineProperty(Material.prototype, "fillMode", {
  31138. /**
  31139. * Gets the material fill mode.
  31140. */
  31141. get: function () {
  31142. return this._fillMode;
  31143. },
  31144. /**
  31145. * Sets the material fill mode.
  31146. */
  31147. set: function (value) {
  31148. if (this._fillMode === value) {
  31149. return;
  31150. }
  31151. this._fillMode = value;
  31152. this.markAsDirty(Material.MiscDirtyFlag);
  31153. },
  31154. enumerable: true,
  31155. configurable: true
  31156. });
  31157. /**
  31158. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31159. * subclasses should override adding information pertainent to themselves.
  31160. * @returns - String with material information.
  31161. */
  31162. Material.prototype.toString = function (fullDetails) {
  31163. var ret = "Name: " + this.name;
  31164. if (fullDetails) {
  31165. }
  31166. return ret;
  31167. };
  31168. /**
  31169. * Gets the class name of the material.
  31170. * @returns - String with the class name of the material.
  31171. */
  31172. Material.prototype.getClassName = function () {
  31173. return "Material";
  31174. };
  31175. Object.defineProperty(Material.prototype, "isFrozen", {
  31176. /**
  31177. * Specifies if updates for the material been locked.
  31178. */
  31179. get: function () {
  31180. return this.checkReadyOnlyOnce;
  31181. },
  31182. enumerable: true,
  31183. configurable: true
  31184. });
  31185. /**
  31186. * Locks updates for the material.
  31187. */
  31188. Material.prototype.freeze = function () {
  31189. this.checkReadyOnlyOnce = true;
  31190. };
  31191. /**
  31192. * Unlocks updates for the material.
  31193. */
  31194. Material.prototype.unfreeze = function () {
  31195. this.checkReadyOnlyOnce = false;
  31196. };
  31197. /**
  31198. * Specifies if the material is ready to be used.
  31199. * @param mesh - BJS mesh.
  31200. * @param useInstances - Specifies if instances should be used.
  31201. * @returns - Boolean indicating if the material is ready to be used.
  31202. */
  31203. Material.prototype.isReady = function (mesh, useInstances) {
  31204. return true;
  31205. };
  31206. /**
  31207. * Specifies that the submesh is ready to be used.
  31208. * @param mesh - BJS mesh.
  31209. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31210. * @param useInstances - Specifies that instances should be used.
  31211. * @returns - boolean indicating that the submesh is ready or not.
  31212. */
  31213. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31214. return false;
  31215. };
  31216. /**
  31217. * Returns the material effect.
  31218. * @returns - Nullable material effect.
  31219. */
  31220. Material.prototype.getEffect = function () {
  31221. return this._effect;
  31222. };
  31223. /**
  31224. * Returns the BJS scene.
  31225. * @returns - BJS Scene.
  31226. */
  31227. Material.prototype.getScene = function () {
  31228. return this._scene;
  31229. };
  31230. /**
  31231. * Specifies if the material will require alpha blending
  31232. * @returns - Boolean specifying if alpha blending is needed.
  31233. */
  31234. Material.prototype.needAlphaBlending = function () {
  31235. return (this.alpha < 1.0);
  31236. };
  31237. /**
  31238. * Specifies if the mesh will require alpha blending.
  31239. * @param mesh - BJS mesh.
  31240. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31241. */
  31242. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31243. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31244. };
  31245. /**
  31246. * Specifies if this material should be rendered in alpha test mode.
  31247. * @returns - Boolean specifying if an alpha test is needed.
  31248. */
  31249. Material.prototype.needAlphaTesting = function () {
  31250. return false;
  31251. };
  31252. /**
  31253. * Gets the texture used for the alpha test.
  31254. * @returns - Nullable alpha test texture.
  31255. */
  31256. Material.prototype.getAlphaTestTexture = function () {
  31257. return null;
  31258. };
  31259. /**
  31260. * Marks the material to indicate that it needs to be re-calculated.
  31261. */
  31262. Material.prototype.markDirty = function () {
  31263. this._wasPreviouslyReady = false;
  31264. };
  31265. Material.prototype._preBind = function (effect, overrideOrientation) {
  31266. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31267. var engine = this._scene.getEngine();
  31268. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31269. var reverse = orientation === Material.ClockWiseSideOrientation;
  31270. engine.enableEffect(effect ? effect : this._effect);
  31271. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31272. return reverse;
  31273. };
  31274. /**
  31275. * Binds the material to the mesh.
  31276. * @param world - World transformation matrix.
  31277. * @param mesh - Mesh to bind the material to.
  31278. */
  31279. Material.prototype.bind = function (world, mesh) {
  31280. };
  31281. /**
  31282. * Binds the submesh to the material.
  31283. * @param world - World transformation matrix.
  31284. * @param mesh - Mesh containing the submesh.
  31285. * @param subMesh - Submesh to bind the material to.
  31286. */
  31287. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31288. };
  31289. /**
  31290. * Binds the world matrix to the material.
  31291. * @param world - World transformation matrix.
  31292. */
  31293. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31294. };
  31295. /**
  31296. * Binds the scene's uniform buffer to the effect.
  31297. * @param effect - Effect to bind to the scene uniform buffer.
  31298. * @param sceneUbo - Scene uniform buffer.
  31299. */
  31300. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  31301. sceneUbo.bindToEffect(effect, "Scene");
  31302. };
  31303. /**
  31304. * Binds the view matrix to the effect.
  31305. * @param effect - Effect to bind the view matrix to.
  31306. */
  31307. Material.prototype.bindView = function (effect) {
  31308. if (!this._useUBO) {
  31309. effect.setMatrix("view", this.getScene().getViewMatrix());
  31310. }
  31311. else {
  31312. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31313. }
  31314. };
  31315. /**
  31316. * Binds the view projection matrix to the effect.
  31317. * @param effect - Effect to bind the view projection matrix to.
  31318. */
  31319. Material.prototype.bindViewProjection = function (effect) {
  31320. if (!this._useUBO) {
  31321. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  31322. }
  31323. else {
  31324. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31325. }
  31326. };
  31327. /**
  31328. * Specifies if material alpha testing should be turned on for the mesh.
  31329. * @param mesh - BJS mesh.
  31330. */
  31331. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  31332. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  31333. };
  31334. /**
  31335. * Processes to execute after binding the material to a mesh.
  31336. * @param mesh - BJS mesh.
  31337. */
  31338. Material.prototype._afterBind = function (mesh) {
  31339. this._scene._cachedMaterial = this;
  31340. if (mesh) {
  31341. this._scene._cachedVisibility = mesh.visibility;
  31342. }
  31343. else {
  31344. this._scene._cachedVisibility = 1;
  31345. }
  31346. if (mesh) {
  31347. this.onBindObservable.notifyObservers(mesh);
  31348. }
  31349. if (this.disableDepthWrite) {
  31350. var engine = this._scene.getEngine();
  31351. this._cachedDepthWriteState = engine.getDepthWrite();
  31352. engine.setDepthWrite(false);
  31353. }
  31354. };
  31355. /**
  31356. * Unbinds the material from the mesh.
  31357. */
  31358. Material.prototype.unbind = function () {
  31359. this.onUnBindObservable.notifyObservers(this);
  31360. if (this.disableDepthWrite) {
  31361. var engine = this._scene.getEngine();
  31362. engine.setDepthWrite(this._cachedDepthWriteState);
  31363. }
  31364. };
  31365. /**
  31366. * Gets the active textures from the material.
  31367. * @returns - Array of textures.
  31368. */
  31369. Material.prototype.getActiveTextures = function () {
  31370. return [];
  31371. };
  31372. /**
  31373. * Specifies if the material uses a texture.
  31374. * @param texture - Texture to check against the material.
  31375. * @returns - Boolean specifying if the material uses the texture.
  31376. */
  31377. Material.prototype.hasTexture = function (texture) {
  31378. return false;
  31379. };
  31380. /**
  31381. * Makes a duplicate of the material, and gives it a new name.
  31382. * @param name - Name to call the duplicated material.
  31383. * @returns - Nullable cloned material
  31384. */
  31385. Material.prototype.clone = function (name) {
  31386. return null;
  31387. };
  31388. /**
  31389. * Gets the meshes bound to the material.
  31390. * @returns - Array of meshes bound to the material.
  31391. */
  31392. Material.prototype.getBindedMeshes = function () {
  31393. var result = new Array();
  31394. for (var index = 0; index < this._scene.meshes.length; index++) {
  31395. var mesh = this._scene.meshes[index];
  31396. if (mesh.material === this) {
  31397. result.push(mesh);
  31398. }
  31399. }
  31400. return result;
  31401. };
  31402. /**
  31403. * Force shader compilation
  31404. * @param mesh - BJS mesh.
  31405. * @param onCompiled - function to execute once the material is compiled.
  31406. * @param options - options to pass to this function.
  31407. */
  31408. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  31409. var _this = this;
  31410. var localOptions = __assign({ clipPlane: false }, options);
  31411. var subMesh = new BABYLON.BaseSubMesh();
  31412. var scene = this.getScene();
  31413. var checkReady = function () {
  31414. if (!_this._scene || !_this._scene.getEngine()) {
  31415. return;
  31416. }
  31417. if (subMesh._materialDefines) {
  31418. subMesh._materialDefines._renderId = -1;
  31419. }
  31420. var clipPlaneState = scene.clipPlane;
  31421. if (localOptions.clipPlane) {
  31422. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  31423. }
  31424. if (_this.storeEffectOnSubMeshes) {
  31425. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  31426. if (onCompiled) {
  31427. onCompiled(_this);
  31428. }
  31429. }
  31430. else {
  31431. setTimeout(checkReady, 16);
  31432. }
  31433. }
  31434. else {
  31435. if (_this.isReady(mesh)) {
  31436. if (onCompiled) {
  31437. onCompiled(_this);
  31438. }
  31439. }
  31440. else {
  31441. setTimeout(checkReady, 16);
  31442. }
  31443. }
  31444. if (localOptions.clipPlane) {
  31445. scene.clipPlane = clipPlaneState;
  31446. }
  31447. };
  31448. checkReady();
  31449. };
  31450. /**
  31451. * Force shader compilation.
  31452. * @param mesh The mesh that will use this material
  31453. * @param options Additional options for compiling the shaders
  31454. * @returns A promise that resolves when the compilation completes
  31455. */
  31456. Material.prototype.forceCompilationAsync = function (mesh, options) {
  31457. var _this = this;
  31458. return new Promise(function (resolve) {
  31459. _this.forceCompilation(mesh, function () {
  31460. resolve();
  31461. }, options);
  31462. });
  31463. };
  31464. /**
  31465. * Marks a define in the material to indicate that it needs to be re-computed.
  31466. * @param flag - Material define flag.
  31467. */
  31468. Material.prototype.markAsDirty = function (flag) {
  31469. if (flag & Material.TextureDirtyFlag) {
  31470. this._markAllSubMeshesAsTexturesDirty();
  31471. }
  31472. if (flag & Material.LightDirtyFlag) {
  31473. this._markAllSubMeshesAsLightsDirty();
  31474. }
  31475. if (flag & Material.FresnelDirtyFlag) {
  31476. this._markAllSubMeshesAsFresnelDirty();
  31477. }
  31478. if (flag & Material.AttributesDirtyFlag) {
  31479. this._markAllSubMeshesAsAttributesDirty();
  31480. }
  31481. if (flag & Material.MiscDirtyFlag) {
  31482. this._markAllSubMeshesAsMiscDirty();
  31483. }
  31484. this.getScene().resetCachedMaterial();
  31485. };
  31486. /**
  31487. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  31488. * @param func - function which checks material defines against the submeshes.
  31489. */
  31490. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  31491. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  31492. var mesh = _a[_i];
  31493. if (!mesh.subMeshes) {
  31494. continue;
  31495. }
  31496. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  31497. var subMesh = _c[_b];
  31498. if (subMesh.getMaterial() !== this) {
  31499. continue;
  31500. }
  31501. if (!subMesh._materialDefines) {
  31502. continue;
  31503. }
  31504. func(subMesh._materialDefines);
  31505. }
  31506. }
  31507. };
  31508. /**
  31509. * Indicates that image processing needs to be re-calculated for all submeshes.
  31510. */
  31511. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  31512. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  31513. };
  31514. /**
  31515. * Indicates that textures need to be re-calculated for all submeshes.
  31516. */
  31517. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  31518. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  31519. };
  31520. /**
  31521. * Indicates that fresnel needs to be re-calculated for all submeshes.
  31522. */
  31523. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  31524. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  31525. };
  31526. /**
  31527. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  31528. */
  31529. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  31530. this._markAllSubMeshesAsDirty(function (defines) {
  31531. defines.markAsFresnelDirty();
  31532. defines.markAsMiscDirty();
  31533. });
  31534. };
  31535. /**
  31536. * Indicates that lights need to be re-calculated for all submeshes.
  31537. */
  31538. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  31539. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  31540. };
  31541. /**
  31542. * Indicates that attributes need to be re-calculated for all submeshes.
  31543. */
  31544. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  31545. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  31546. };
  31547. /**
  31548. * Indicates that misc needs to be re-calculated for all submeshes.
  31549. */
  31550. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  31551. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  31552. };
  31553. /**
  31554. * Indicates that textures and misc need to be re-calculated for all submeshes.
  31555. */
  31556. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  31557. this._markAllSubMeshesAsDirty(function (defines) {
  31558. defines.markAsTexturesDirty();
  31559. defines.markAsMiscDirty();
  31560. });
  31561. };
  31562. /**
  31563. * Disposes the material.
  31564. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  31565. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  31566. */
  31567. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31568. // Animations
  31569. this.getScene().stopAnimation(this);
  31570. // Remove from scene
  31571. var index = this._scene.materials.indexOf(this);
  31572. if (index >= 0) {
  31573. this._scene.materials.splice(index, 1);
  31574. }
  31575. // Remove from meshes
  31576. for (index = 0; index < this._scene.meshes.length; index++) {
  31577. var mesh = this._scene.meshes[index];
  31578. if (mesh.material === this) {
  31579. mesh.material = null;
  31580. if (mesh.geometry) {
  31581. var geometry = (mesh.geometry);
  31582. if (this.storeEffectOnSubMeshes) {
  31583. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  31584. var subMesh = _a[_i];
  31585. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  31586. if (forceDisposeEffect && subMesh._materialEffect) {
  31587. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  31588. }
  31589. }
  31590. }
  31591. else {
  31592. geometry._releaseVertexArrayObject(this._effect);
  31593. }
  31594. }
  31595. }
  31596. }
  31597. this._uniformBuffer.dispose();
  31598. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  31599. if (forceDisposeEffect && this._effect) {
  31600. if (!this.storeEffectOnSubMeshes) {
  31601. this._scene.getEngine()._releaseEffect(this._effect);
  31602. }
  31603. this._effect = null;
  31604. }
  31605. // Callback
  31606. this.onDisposeObservable.notifyObservers(this);
  31607. this.onDisposeObservable.clear();
  31608. this.onBindObservable.clear();
  31609. this.onUnBindObservable.clear();
  31610. };
  31611. /**
  31612. * Serializes this material.
  31613. * @returns - serialized material object.
  31614. */
  31615. Material.prototype.serialize = function () {
  31616. return BABYLON.SerializationHelper.Serialize(this);
  31617. };
  31618. /**
  31619. * Creates a MultiMaterial from parse MultiMaterial data.
  31620. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  31621. * @param scene - BJS scene.
  31622. * @returns - MultiMaterial.
  31623. */
  31624. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  31625. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  31626. multiMaterial.id = parsedMultiMaterial.id;
  31627. if (BABYLON.Tags) {
  31628. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  31629. }
  31630. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  31631. var subMatId = parsedMultiMaterial.materials[matIndex];
  31632. if (subMatId) {
  31633. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  31634. }
  31635. else {
  31636. multiMaterial.subMaterials.push(null);
  31637. }
  31638. }
  31639. return multiMaterial;
  31640. };
  31641. /**
  31642. * Creates a material from parsed material data.
  31643. * @param parsedMaterial - Parsed material data.
  31644. * @param scene - BJS scene.
  31645. * @param rootUrl - Root URL containing the material information.
  31646. * @returns - Parsed material.
  31647. */
  31648. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  31649. if (!parsedMaterial.customType) {
  31650. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  31651. }
  31652. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  31653. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  31654. if (!BABYLON.LegacyPBRMaterial) {
  31655. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  31656. return;
  31657. }
  31658. }
  31659. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  31660. return materialType.Parse(parsedMaterial, scene, rootUrl);
  31661. ;
  31662. };
  31663. // Triangle views
  31664. Material._TriangleFillMode = 0;
  31665. Material._WireFrameFillMode = 1;
  31666. Material._PointFillMode = 2;
  31667. // Draw modes
  31668. Material._PointListDrawMode = 3;
  31669. Material._LineListDrawMode = 4;
  31670. Material._LineLoopDrawMode = 5;
  31671. Material._LineStripDrawMode = 6;
  31672. Material._TriangleStripDrawMode = 7;
  31673. Material._TriangleFanDrawMode = 8;
  31674. /**
  31675. * Stores the clock-wise side orientation.
  31676. */
  31677. Material._ClockWiseSideOrientation = 0;
  31678. /**
  31679. * Stores the counter clock-wise side orientation.
  31680. */
  31681. Material._CounterClockWiseSideOrientation = 1;
  31682. /**
  31683. * The dirty texture flag value.
  31684. */
  31685. Material._TextureDirtyFlag = 1;
  31686. /**
  31687. * The dirty light flag value.
  31688. */
  31689. Material._LightDirtyFlag = 2;
  31690. /**
  31691. * The dirty fresnel flag value.
  31692. */
  31693. Material._FresnelDirtyFlag = 4;
  31694. /**
  31695. * The dirty attribute flag value.
  31696. */
  31697. Material._AttributesDirtyFlag = 8;
  31698. /**
  31699. * The dirty misc flag value.
  31700. */
  31701. Material._MiscDirtyFlag = 16;
  31702. __decorate([
  31703. BABYLON.serialize()
  31704. ], Material.prototype, "id", void 0);
  31705. __decorate([
  31706. BABYLON.serialize()
  31707. ], Material.prototype, "name", void 0);
  31708. __decorate([
  31709. BABYLON.serialize()
  31710. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  31711. __decorate([
  31712. BABYLON.serialize()
  31713. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  31714. __decorate([
  31715. BABYLON.serialize()
  31716. ], Material.prototype, "state", void 0);
  31717. __decorate([
  31718. BABYLON.serialize("alpha")
  31719. ], Material.prototype, "_alpha", void 0);
  31720. __decorate([
  31721. BABYLON.serialize("backFaceCulling")
  31722. ], Material.prototype, "_backFaceCulling", void 0);
  31723. __decorate([
  31724. BABYLON.serialize()
  31725. ], Material.prototype, "sideOrientation", void 0);
  31726. __decorate([
  31727. BABYLON.serialize("alphaMode")
  31728. ], Material.prototype, "_alphaMode", void 0);
  31729. __decorate([
  31730. BABYLON.serialize()
  31731. ], Material.prototype, "_needDepthPrePass", void 0);
  31732. __decorate([
  31733. BABYLON.serialize()
  31734. ], Material.prototype, "disableDepthWrite", void 0);
  31735. __decorate([
  31736. BABYLON.serialize()
  31737. ], Material.prototype, "forceDepthWrite", void 0);
  31738. __decorate([
  31739. BABYLON.serialize()
  31740. ], Material.prototype, "separateCullingPass", void 0);
  31741. __decorate([
  31742. BABYLON.serialize("fogEnabled")
  31743. ], Material.prototype, "_fogEnabled", void 0);
  31744. __decorate([
  31745. BABYLON.serialize()
  31746. ], Material.prototype, "pointSize", void 0);
  31747. __decorate([
  31748. BABYLON.serialize()
  31749. ], Material.prototype, "zOffset", void 0);
  31750. __decorate([
  31751. BABYLON.serialize()
  31752. ], Material.prototype, "wireframe", null);
  31753. __decorate([
  31754. BABYLON.serialize()
  31755. ], Material.prototype, "pointsCloud", null);
  31756. __decorate([
  31757. BABYLON.serialize()
  31758. ], Material.prototype, "fillMode", null);
  31759. return Material;
  31760. }());
  31761. BABYLON.Material = Material;
  31762. })(BABYLON || (BABYLON = {}));
  31763. //# sourceMappingURL=babylon.material.js.map
  31764. var BABYLON;
  31765. (function (BABYLON) {
  31766. var UniformBuffer = /** @class */ (function () {
  31767. /**
  31768. * Uniform buffer objects.
  31769. *
  31770. * Handles blocks of uniform on the GPU.
  31771. *
  31772. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  31773. *
  31774. * For more information, please refer to :
  31775. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  31776. */
  31777. function UniformBuffer(engine, data, dynamic) {
  31778. this._engine = engine;
  31779. this._noUBO = !engine.supportsUniformBuffers;
  31780. this._dynamic = dynamic;
  31781. this._data = data || [];
  31782. this._uniformLocations = {};
  31783. this._uniformSizes = {};
  31784. this._uniformLocationPointer = 0;
  31785. this._needSync = false;
  31786. if (this._noUBO) {
  31787. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  31788. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  31789. this.updateFloat = this._updateFloatForEffect;
  31790. this.updateFloat2 = this._updateFloat2ForEffect;
  31791. this.updateFloat3 = this._updateFloat3ForEffect;
  31792. this.updateFloat4 = this._updateFloat4ForEffect;
  31793. this.updateMatrix = this._updateMatrixForEffect;
  31794. this.updateVector3 = this._updateVector3ForEffect;
  31795. this.updateVector4 = this._updateVector4ForEffect;
  31796. this.updateColor3 = this._updateColor3ForEffect;
  31797. this.updateColor4 = this._updateColor4ForEffect;
  31798. }
  31799. else {
  31800. this._engine._uniformBuffers.push(this);
  31801. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  31802. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  31803. this.updateFloat = this._updateFloatForUniform;
  31804. this.updateFloat2 = this._updateFloat2ForUniform;
  31805. this.updateFloat3 = this._updateFloat3ForUniform;
  31806. this.updateFloat4 = this._updateFloat4ForUniform;
  31807. this.updateMatrix = this._updateMatrixForUniform;
  31808. this.updateVector3 = this._updateVector3ForUniform;
  31809. this.updateVector4 = this._updateVector4ForUniform;
  31810. this.updateColor3 = this._updateColor3ForUniform;
  31811. this.updateColor4 = this._updateColor4ForUniform;
  31812. }
  31813. }
  31814. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  31815. // Properties
  31816. /**
  31817. * Indicates if the buffer is using the WebGL2 UBO implementation,
  31818. * or just falling back on setUniformXXX calls.
  31819. */
  31820. get: function () {
  31821. return !this._noUBO;
  31822. },
  31823. enumerable: true,
  31824. configurable: true
  31825. });
  31826. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  31827. /**
  31828. * Indicates if the WebGL underlying uniform buffer is in sync
  31829. * with the javascript cache data.
  31830. */
  31831. get: function () {
  31832. return !this._needSync;
  31833. },
  31834. enumerable: true,
  31835. configurable: true
  31836. });
  31837. /**
  31838. * Indicates if the WebGL underlying uniform buffer is dynamic.
  31839. * Also, a dynamic UniformBuffer will disable cache verification and always
  31840. * update the underlying WebGL uniform buffer to the GPU.
  31841. */
  31842. UniformBuffer.prototype.isDynamic = function () {
  31843. return this._dynamic !== undefined;
  31844. };
  31845. /**
  31846. * The data cache on JS side.
  31847. */
  31848. UniformBuffer.prototype.getData = function () {
  31849. return this._bufferData;
  31850. };
  31851. /**
  31852. * The underlying WebGL Uniform buffer.
  31853. */
  31854. UniformBuffer.prototype.getBuffer = function () {
  31855. return this._buffer;
  31856. };
  31857. /**
  31858. * std140 layout specifies how to align data within an UBO structure.
  31859. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  31860. * for specs.
  31861. */
  31862. UniformBuffer.prototype._fillAlignment = function (size) {
  31863. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  31864. // and 4x4 matrices
  31865. // TODO : change if other types are used
  31866. var alignment;
  31867. if (size <= 2) {
  31868. alignment = size;
  31869. }
  31870. else {
  31871. alignment = 4;
  31872. }
  31873. if ((this._uniformLocationPointer % alignment) !== 0) {
  31874. var oldPointer = this._uniformLocationPointer;
  31875. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  31876. var diff = this._uniformLocationPointer - oldPointer;
  31877. for (var i = 0; i < diff; i++) {
  31878. this._data.push(0);
  31879. }
  31880. }
  31881. };
  31882. /**
  31883. * Adds an uniform in the buffer.
  31884. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  31885. * for the layout to be correct !
  31886. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31887. * @param {number|number[]} size Data size, or data directly.
  31888. */
  31889. UniformBuffer.prototype.addUniform = function (name, size) {
  31890. if (this._noUBO) {
  31891. return;
  31892. }
  31893. if (this._uniformLocations[name] !== undefined) {
  31894. // Already existing uniform
  31895. return;
  31896. }
  31897. // This function must be called in the order of the shader layout !
  31898. // size can be the size of the uniform, or data directly
  31899. var data;
  31900. if (size instanceof Array) {
  31901. data = size;
  31902. size = data.length;
  31903. }
  31904. else {
  31905. size = size;
  31906. data = [];
  31907. // Fill with zeros
  31908. for (var i = 0; i < size; i++) {
  31909. data.push(0);
  31910. }
  31911. }
  31912. this._fillAlignment(size);
  31913. this._uniformSizes[name] = size;
  31914. this._uniformLocations[name] = this._uniformLocationPointer;
  31915. this._uniformLocationPointer += size;
  31916. for (var i = 0; i < size; i++) {
  31917. this._data.push(data[i]);
  31918. }
  31919. this._needSync = true;
  31920. };
  31921. /**
  31922. * Wrapper for addUniform.
  31923. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31924. * @param {Matrix} mat A 4x4 matrix.
  31925. */
  31926. UniformBuffer.prototype.addMatrix = function (name, mat) {
  31927. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  31928. };
  31929. /**
  31930. * Wrapper for addUniform.
  31931. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31932. * @param {number} x
  31933. * @param {number} y
  31934. */
  31935. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  31936. var temp = [x, y];
  31937. this.addUniform(name, temp);
  31938. };
  31939. /**
  31940. * Wrapper for addUniform.
  31941. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31942. * @param {number} x
  31943. * @param {number} y
  31944. * @param {number} z
  31945. */
  31946. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  31947. var temp = [x, y, z];
  31948. this.addUniform(name, temp);
  31949. };
  31950. /**
  31951. * Wrapper for addUniform.
  31952. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31953. * @param {Color3} color
  31954. */
  31955. UniformBuffer.prototype.addColor3 = function (name, color) {
  31956. var temp = new Array();
  31957. color.toArray(temp);
  31958. this.addUniform(name, temp);
  31959. };
  31960. /**
  31961. * Wrapper for addUniform.
  31962. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31963. * @param {Color3} color
  31964. * @param {number} alpha
  31965. */
  31966. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  31967. var temp = new Array();
  31968. color.toArray(temp);
  31969. temp.push(alpha);
  31970. this.addUniform(name, temp);
  31971. };
  31972. /**
  31973. * Wrapper for addUniform.
  31974. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31975. * @param {Vector3} vector
  31976. */
  31977. UniformBuffer.prototype.addVector3 = function (name, vector) {
  31978. var temp = new Array();
  31979. vector.toArray(temp);
  31980. this.addUniform(name, temp);
  31981. };
  31982. /**
  31983. * Wrapper for addUniform.
  31984. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31985. */
  31986. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  31987. this.addUniform(name, 12);
  31988. };
  31989. /**
  31990. * Wrapper for addUniform.
  31991. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31992. */
  31993. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  31994. this.addUniform(name, 8);
  31995. };
  31996. /**
  31997. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  31998. */
  31999. UniformBuffer.prototype.create = function () {
  32000. if (this._noUBO) {
  32001. return;
  32002. }
  32003. if (this._buffer) {
  32004. return; // nothing to do
  32005. }
  32006. // See spec, alignment must be filled as a vec4
  32007. this._fillAlignment(4);
  32008. this._bufferData = new Float32Array(this._data);
  32009. this._rebuild();
  32010. this._needSync = true;
  32011. };
  32012. UniformBuffer.prototype._rebuild = function () {
  32013. if (this._noUBO) {
  32014. return;
  32015. }
  32016. if (this._dynamic) {
  32017. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32018. }
  32019. else {
  32020. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32021. }
  32022. };
  32023. /**
  32024. * Updates the WebGL Uniform Buffer on the GPU.
  32025. * If the `dynamic` flag is set to true, no cache comparison is done.
  32026. * Otherwise, the buffer will be updated only if the cache differs.
  32027. */
  32028. UniformBuffer.prototype.update = function () {
  32029. if (!this._buffer) {
  32030. this.create();
  32031. return;
  32032. }
  32033. if (!this._dynamic && !this._needSync) {
  32034. return;
  32035. }
  32036. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32037. this._needSync = false;
  32038. };
  32039. /**
  32040. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32041. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32042. * @param {number[]|Float32Array} data Flattened data
  32043. * @param {number} size Size of the data.
  32044. */
  32045. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32046. var location = this._uniformLocations[uniformName];
  32047. if (location === undefined) {
  32048. if (this._buffer) {
  32049. // Cannot add an uniform if the buffer is already created
  32050. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32051. return;
  32052. }
  32053. this.addUniform(uniformName, size);
  32054. location = this._uniformLocations[uniformName];
  32055. }
  32056. if (!this._buffer) {
  32057. this.create();
  32058. }
  32059. if (!this._dynamic) {
  32060. // Cache for static uniform buffers
  32061. var changed = false;
  32062. for (var i = 0; i < size; i++) {
  32063. if (this._bufferData[location + i] !== data[i]) {
  32064. changed = true;
  32065. this._bufferData[location + i] = data[i];
  32066. }
  32067. }
  32068. this._needSync = this._needSync || changed;
  32069. }
  32070. else {
  32071. // No cache for dynamic
  32072. for (var i = 0; i < size; i++) {
  32073. this._bufferData[location + i] = data[i];
  32074. }
  32075. }
  32076. };
  32077. // Update methods
  32078. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32079. // To match std140, matrix must be realigned
  32080. for (var i = 0; i < 3; i++) {
  32081. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32082. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32083. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32084. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32085. }
  32086. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32087. };
  32088. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32089. this._currentEffect.setMatrix3x3(name, matrix);
  32090. };
  32091. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32092. this._currentEffect.setMatrix2x2(name, matrix);
  32093. };
  32094. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32095. // To match std140, matrix must be realigned
  32096. for (var i = 0; i < 2; i++) {
  32097. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32098. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32099. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32100. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32101. }
  32102. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32103. };
  32104. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32105. this._currentEffect.setFloat(name, x);
  32106. };
  32107. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32108. UniformBuffer._tempBuffer[0] = x;
  32109. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32110. };
  32111. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32112. if (suffix === void 0) { suffix = ""; }
  32113. this._currentEffect.setFloat2(name + suffix, x, y);
  32114. };
  32115. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32116. if (suffix === void 0) { suffix = ""; }
  32117. UniformBuffer._tempBuffer[0] = x;
  32118. UniformBuffer._tempBuffer[1] = y;
  32119. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32120. };
  32121. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32122. if (suffix === void 0) { suffix = ""; }
  32123. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32124. };
  32125. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32126. if (suffix === void 0) { suffix = ""; }
  32127. UniformBuffer._tempBuffer[0] = x;
  32128. UniformBuffer._tempBuffer[1] = y;
  32129. UniformBuffer._tempBuffer[2] = z;
  32130. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32131. };
  32132. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32133. if (suffix === void 0) { suffix = ""; }
  32134. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32135. };
  32136. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32137. if (suffix === void 0) { suffix = ""; }
  32138. UniformBuffer._tempBuffer[0] = x;
  32139. UniformBuffer._tempBuffer[1] = y;
  32140. UniformBuffer._tempBuffer[2] = z;
  32141. UniformBuffer._tempBuffer[3] = w;
  32142. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32143. };
  32144. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32145. this._currentEffect.setMatrix(name, mat);
  32146. };
  32147. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32148. this.updateUniform(name, mat.toArray(), 16);
  32149. };
  32150. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32151. this._currentEffect.setVector3(name, vector);
  32152. };
  32153. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32154. vector.toArray(UniformBuffer._tempBuffer);
  32155. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32156. };
  32157. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32158. this._currentEffect.setVector4(name, vector);
  32159. };
  32160. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32161. vector.toArray(UniformBuffer._tempBuffer);
  32162. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32163. };
  32164. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32165. if (suffix === void 0) { suffix = ""; }
  32166. this._currentEffect.setColor3(name + suffix, color);
  32167. };
  32168. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32169. if (suffix === void 0) { suffix = ""; }
  32170. color.toArray(UniformBuffer._tempBuffer);
  32171. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32172. };
  32173. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32174. if (suffix === void 0) { suffix = ""; }
  32175. this._currentEffect.setColor4(name + suffix, color, alpha);
  32176. };
  32177. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32178. if (suffix === void 0) { suffix = ""; }
  32179. color.toArray(UniformBuffer._tempBuffer);
  32180. UniformBuffer._tempBuffer[3] = alpha;
  32181. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32182. };
  32183. /**
  32184. * Sets a sampler uniform on the effect.
  32185. * @param {string} name Name of the sampler.
  32186. * @param {Texture} texture
  32187. */
  32188. UniformBuffer.prototype.setTexture = function (name, texture) {
  32189. this._currentEffect.setTexture(name, texture);
  32190. };
  32191. /**
  32192. * Directly updates the value of the uniform in the cache AND on the GPU.
  32193. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32194. * @param {number[]|Float32Array} data Flattened data
  32195. */
  32196. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32197. this.updateUniform(uniformName, data, data.length);
  32198. this.update();
  32199. };
  32200. /**
  32201. * Binds this uniform buffer to an effect.
  32202. * @param {Effect} effect
  32203. * @param {string} name Name of the uniform block in the shader.
  32204. */
  32205. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32206. this._currentEffect = effect;
  32207. if (this._noUBO || !this._buffer) {
  32208. return;
  32209. }
  32210. effect.bindUniformBuffer(this._buffer, name);
  32211. };
  32212. /**
  32213. * Disposes the uniform buffer.
  32214. */
  32215. UniformBuffer.prototype.dispose = function () {
  32216. if (this._noUBO) {
  32217. return;
  32218. }
  32219. var index = this._engine._uniformBuffers.indexOf(this);
  32220. if (index !== -1) {
  32221. this._engine._uniformBuffers.splice(index, 1);
  32222. }
  32223. if (!this._buffer) {
  32224. return;
  32225. }
  32226. if (this._engine._releaseBuffer(this._buffer)) {
  32227. this._buffer = null;
  32228. }
  32229. };
  32230. // Pool for avoiding memory leaks
  32231. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32232. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32233. return UniformBuffer;
  32234. }());
  32235. BABYLON.UniformBuffer = UniformBuffer;
  32236. })(BABYLON || (BABYLON = {}));
  32237. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32238. var BABYLON;
  32239. (function (BABYLON) {
  32240. var VertexData = /** @class */ (function () {
  32241. function VertexData() {
  32242. }
  32243. VertexData.prototype.set = function (data, kind) {
  32244. switch (kind) {
  32245. case BABYLON.VertexBuffer.PositionKind:
  32246. this.positions = data;
  32247. break;
  32248. case BABYLON.VertexBuffer.NormalKind:
  32249. this.normals = data;
  32250. break;
  32251. case BABYLON.VertexBuffer.TangentKind:
  32252. this.tangents = data;
  32253. break;
  32254. case BABYLON.VertexBuffer.UVKind:
  32255. this.uvs = data;
  32256. break;
  32257. case BABYLON.VertexBuffer.UV2Kind:
  32258. this.uvs2 = data;
  32259. break;
  32260. case BABYLON.VertexBuffer.UV3Kind:
  32261. this.uvs3 = data;
  32262. break;
  32263. case BABYLON.VertexBuffer.UV4Kind:
  32264. this.uvs4 = data;
  32265. break;
  32266. case BABYLON.VertexBuffer.UV5Kind:
  32267. this.uvs5 = data;
  32268. break;
  32269. case BABYLON.VertexBuffer.UV6Kind:
  32270. this.uvs6 = data;
  32271. break;
  32272. case BABYLON.VertexBuffer.ColorKind:
  32273. this.colors = data;
  32274. break;
  32275. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32276. this.matricesIndices = data;
  32277. break;
  32278. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32279. this.matricesWeights = data;
  32280. break;
  32281. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32282. this.matricesIndicesExtra = data;
  32283. break;
  32284. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32285. this.matricesWeightsExtra = data;
  32286. break;
  32287. }
  32288. };
  32289. /**
  32290. * Associates the vertexData to the passed Mesh.
  32291. * Sets it as updatable or not (default `false`).
  32292. * Returns the VertexData.
  32293. */
  32294. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32295. this._applyTo(mesh, updatable);
  32296. return this;
  32297. };
  32298. /**
  32299. * Associates the vertexData to the passed Geometry.
  32300. * Sets it as updatable or not (default `false`).
  32301. * Returns the VertexData.
  32302. */
  32303. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32304. this._applyTo(geometry, updatable);
  32305. return this;
  32306. };
  32307. /**
  32308. * Updates the associated mesh.
  32309. * Returns the VertexData.
  32310. */
  32311. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32312. this._update(mesh);
  32313. return this;
  32314. };
  32315. /**
  32316. * Updates the associated geometry.
  32317. * Returns the VertexData.
  32318. */
  32319. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32320. this._update(geometry);
  32321. return this;
  32322. };
  32323. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32324. if (updatable === void 0) { updatable = false; }
  32325. if (this.positions) {
  32326. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32327. }
  32328. if (this.normals) {
  32329. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32330. }
  32331. if (this.tangents) {
  32332. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  32333. }
  32334. if (this.uvs) {
  32335. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32336. }
  32337. if (this.uvs2) {
  32338. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32339. }
  32340. if (this.uvs3) {
  32341. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32342. }
  32343. if (this.uvs4) {
  32344. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32345. }
  32346. if (this.uvs5) {
  32347. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32348. }
  32349. if (this.uvs6) {
  32350. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32351. }
  32352. if (this.colors) {
  32353. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32354. }
  32355. if (this.matricesIndices) {
  32356. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32357. }
  32358. if (this.matricesWeights) {
  32359. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32360. }
  32361. if (this.matricesIndicesExtra) {
  32362. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32363. }
  32364. if (this.matricesWeightsExtra) {
  32365. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32366. }
  32367. if (this.indices) {
  32368. meshOrGeometry.setIndices(this.indices, null, updatable);
  32369. }
  32370. return this;
  32371. };
  32372. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32373. if (this.positions) {
  32374. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32375. }
  32376. if (this.normals) {
  32377. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32378. }
  32379. if (this.tangents) {
  32380. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  32381. }
  32382. if (this.uvs) {
  32383. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32384. }
  32385. if (this.uvs2) {
  32386. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32387. }
  32388. if (this.uvs3) {
  32389. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32390. }
  32391. if (this.uvs4) {
  32392. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32393. }
  32394. if (this.uvs5) {
  32395. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32396. }
  32397. if (this.uvs6) {
  32398. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32399. }
  32400. if (this.colors) {
  32401. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32402. }
  32403. if (this.matricesIndices) {
  32404. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32405. }
  32406. if (this.matricesWeights) {
  32407. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32408. }
  32409. if (this.matricesIndicesExtra) {
  32410. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32411. }
  32412. if (this.matricesWeightsExtra) {
  32413. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32414. }
  32415. if (this.indices) {
  32416. meshOrGeometry.setIndices(this.indices, null);
  32417. }
  32418. return this;
  32419. };
  32420. /**
  32421. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  32422. * Returns the VertexData.
  32423. */
  32424. VertexData.prototype.transform = function (matrix) {
  32425. var transformed = BABYLON.Vector3.Zero();
  32426. var index;
  32427. if (this.positions) {
  32428. var position = BABYLON.Vector3.Zero();
  32429. for (index = 0; index < this.positions.length; index += 3) {
  32430. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  32431. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  32432. this.positions[index] = transformed.x;
  32433. this.positions[index + 1] = transformed.y;
  32434. this.positions[index + 2] = transformed.z;
  32435. }
  32436. }
  32437. if (this.normals) {
  32438. var normal = BABYLON.Vector3.Zero();
  32439. for (index = 0; index < this.normals.length; index += 3) {
  32440. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  32441. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  32442. this.normals[index] = transformed.x;
  32443. this.normals[index + 1] = transformed.y;
  32444. this.normals[index + 2] = transformed.z;
  32445. }
  32446. }
  32447. if (this.tangents) {
  32448. var tangent = BABYLON.Vector4.Zero();
  32449. var tangentTransformed = BABYLON.Vector4.Zero();
  32450. for (index = 0; index < this.tangents.length; index += 4) {
  32451. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  32452. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  32453. this.tangents[index] = tangentTransformed.x;
  32454. this.tangents[index + 1] = tangentTransformed.y;
  32455. this.tangents[index + 2] = tangentTransformed.z;
  32456. this.tangents[index + 3] = tangentTransformed.w;
  32457. }
  32458. }
  32459. return this;
  32460. };
  32461. /**
  32462. * Merges the passed VertexData into the current one.
  32463. * Returns the modified VertexData.
  32464. */
  32465. VertexData.prototype.merge = function (other) {
  32466. this._validate();
  32467. other._validate();
  32468. if (!this.normals !== !other.normals ||
  32469. !this.tangents !== !other.tangents ||
  32470. !this.uvs !== !other.uvs ||
  32471. !this.uvs2 !== !other.uvs2 ||
  32472. !this.uvs3 !== !other.uvs3 ||
  32473. !this.uvs4 !== !other.uvs4 ||
  32474. !this.uvs5 !== !other.uvs5 ||
  32475. !this.uvs6 !== !other.uvs6 ||
  32476. !this.colors !== !other.colors ||
  32477. !this.matricesIndices !== !other.matricesIndices ||
  32478. !this.matricesWeights !== !other.matricesWeights ||
  32479. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  32480. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  32481. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  32482. }
  32483. if (other.indices) {
  32484. if (!this.indices) {
  32485. this.indices = [];
  32486. }
  32487. var offset = this.positions ? this.positions.length / 3 : 0;
  32488. for (var index = 0; index < other.indices.length; index++) {
  32489. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  32490. this.indices.push(other.indices[index] + offset);
  32491. }
  32492. }
  32493. this.positions = this._mergeElement(this.positions, other.positions);
  32494. this.normals = this._mergeElement(this.normals, other.normals);
  32495. this.tangents = this._mergeElement(this.tangents, other.tangents);
  32496. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32497. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32498. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32499. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32500. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32501. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32502. this.colors = this._mergeElement(this.colors, other.colors);
  32503. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32504. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32505. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32506. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32507. return this;
  32508. };
  32509. VertexData.prototype._mergeElement = function (source, other) {
  32510. if (!source) {
  32511. return other;
  32512. }
  32513. if (!other) {
  32514. return source;
  32515. }
  32516. var len = other.length + source.length;
  32517. var isSrcTypedArray = source instanceof Float32Array;
  32518. var isOthTypedArray = other instanceof Float32Array;
  32519. // use non-loop method when the source is Float32Array
  32520. if (isSrcTypedArray) {
  32521. var ret32 = new Float32Array(len);
  32522. ret32.set(source);
  32523. ret32.set(other, source.length);
  32524. return ret32;
  32525. // source is number[], when other is also use concat
  32526. }
  32527. else if (!isOthTypedArray) {
  32528. return source.concat(other);
  32529. // source is a number[], but other is a Float32Array, loop required
  32530. }
  32531. else {
  32532. var ret = source.slice(0); // copy source to a separate array
  32533. for (var i = 0, len = other.length; i < len; i++) {
  32534. ret.push(other[i]);
  32535. }
  32536. return ret;
  32537. }
  32538. };
  32539. VertexData.prototype._validate = function () {
  32540. if (!this.positions) {
  32541. throw new Error("Positions are required");
  32542. }
  32543. var getElementCount = function (kind, values) {
  32544. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  32545. if ((values.length % stride) !== 0) {
  32546. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  32547. }
  32548. return values.length / stride;
  32549. };
  32550. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  32551. var validateElementCount = function (kind, values) {
  32552. var elementCount = getElementCount(kind, values);
  32553. if (elementCount !== positionsElementCount) {
  32554. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  32555. }
  32556. };
  32557. if (this.normals)
  32558. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  32559. if (this.tangents)
  32560. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  32561. if (this.uvs)
  32562. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  32563. if (this.uvs2)
  32564. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  32565. if (this.uvs3)
  32566. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  32567. if (this.uvs4)
  32568. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  32569. if (this.uvs5)
  32570. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  32571. if (this.uvs6)
  32572. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  32573. if (this.colors)
  32574. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  32575. if (this.matricesIndices)
  32576. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  32577. if (this.matricesWeights)
  32578. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  32579. if (this.matricesIndicesExtra)
  32580. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  32581. if (this.matricesWeightsExtra)
  32582. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  32583. };
  32584. /**
  32585. * Serializes the VertexData.
  32586. * Returns a serialized object.
  32587. */
  32588. VertexData.prototype.serialize = function () {
  32589. var serializationObject = this.serialize();
  32590. if (this.positions) {
  32591. serializationObject.positions = this.positions;
  32592. }
  32593. if (this.normals) {
  32594. serializationObject.normals = this.normals;
  32595. }
  32596. if (this.tangents) {
  32597. serializationObject.tangents = this.tangents;
  32598. }
  32599. if (this.uvs) {
  32600. serializationObject.uvs = this.uvs;
  32601. }
  32602. if (this.uvs2) {
  32603. serializationObject.uvs2 = this.uvs2;
  32604. }
  32605. if (this.uvs3) {
  32606. serializationObject.uvs3 = this.uvs3;
  32607. }
  32608. if (this.uvs4) {
  32609. serializationObject.uvs4 = this.uvs4;
  32610. }
  32611. if (this.uvs5) {
  32612. serializationObject.uvs5 = this.uvs5;
  32613. }
  32614. if (this.uvs6) {
  32615. serializationObject.uvs6 = this.uvs6;
  32616. }
  32617. if (this.colors) {
  32618. serializationObject.colors = this.colors;
  32619. }
  32620. if (this.matricesIndices) {
  32621. serializationObject.matricesIndices = this.matricesIndices;
  32622. serializationObject.matricesIndices._isExpanded = true;
  32623. }
  32624. if (this.matricesWeights) {
  32625. serializationObject.matricesWeights = this.matricesWeights;
  32626. }
  32627. if (this.matricesIndicesExtra) {
  32628. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32629. serializationObject.matricesIndicesExtra._isExpanded = true;
  32630. }
  32631. if (this.matricesWeightsExtra) {
  32632. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32633. }
  32634. serializationObject.indices = this.indices;
  32635. return serializationObject;
  32636. };
  32637. // Statics
  32638. /**
  32639. * Returns the object VertexData associated to the passed mesh.
  32640. */
  32641. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  32642. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  32643. };
  32644. /**
  32645. * Returns the object VertexData associated to the passed geometry.
  32646. */
  32647. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  32648. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  32649. };
  32650. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  32651. var result = new VertexData();
  32652. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32653. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  32654. }
  32655. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32656. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  32657. }
  32658. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32659. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  32660. }
  32661. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32662. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  32663. }
  32664. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32665. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  32666. }
  32667. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32668. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  32669. }
  32670. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32671. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  32672. }
  32673. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32674. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  32675. }
  32676. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32677. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  32678. }
  32679. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32680. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  32681. }
  32682. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32683. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  32684. }
  32685. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32686. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  32687. }
  32688. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32689. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  32690. }
  32691. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32692. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  32693. }
  32694. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32695. return result;
  32696. };
  32697. /**
  32698. * Creates the vertexData of the Ribbon.
  32699. */
  32700. VertexData.CreateRibbon = function (options) {
  32701. var pathArray = options.pathArray;
  32702. var closeArray = options.closeArray || false;
  32703. var closePath = options.closePath || false;
  32704. var invertUV = options.invertUV || false;
  32705. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32706. var offset = options.offset || defaultOffset;
  32707. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32708. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32709. var customUV = options.uvs;
  32710. var customColors = options.colors;
  32711. var positions = [];
  32712. var indices = [];
  32713. var normals = [];
  32714. var uvs = [];
  32715. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32716. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32717. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32718. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32719. var minlg; // minimal length among all paths from pathArray
  32720. var lg = []; // array of path lengths : nb of vertex per path
  32721. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32722. var p; // path iterator
  32723. var i; // point iterator
  32724. var j; // point iterator
  32725. // if single path in pathArray
  32726. if (pathArray.length < 2) {
  32727. var ar1 = [];
  32728. var ar2 = [];
  32729. for (i = 0; i < pathArray[0].length - offset; i++) {
  32730. ar1.push(pathArray[0][i]);
  32731. ar2.push(pathArray[0][i + offset]);
  32732. }
  32733. pathArray = [ar1, ar2];
  32734. }
  32735. // positions and horizontal distances (u)
  32736. var idc = 0;
  32737. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  32738. var path;
  32739. var l;
  32740. minlg = pathArray[0].length;
  32741. var vectlg;
  32742. var dist;
  32743. for (p = 0; p < pathArray.length; p++) {
  32744. uTotalDistance[p] = 0;
  32745. us[p] = [0];
  32746. path = pathArray[p];
  32747. l = path.length;
  32748. minlg = (minlg < l) ? minlg : l;
  32749. j = 0;
  32750. while (j < l) {
  32751. positions.push(path[j].x, path[j].y, path[j].z);
  32752. if (j > 0) {
  32753. vectlg = path[j].subtract(path[j - 1]).length();
  32754. dist = vectlg + uTotalDistance[p];
  32755. us[p].push(dist);
  32756. uTotalDistance[p] = dist;
  32757. }
  32758. j++;
  32759. }
  32760. if (closePath) {
  32761. j--;
  32762. positions.push(path[0].x, path[0].y, path[0].z);
  32763. vectlg = path[j].subtract(path[0]).length();
  32764. dist = vectlg + uTotalDistance[p];
  32765. us[p].push(dist);
  32766. uTotalDistance[p] = dist;
  32767. }
  32768. lg[p] = l + closePathCorr;
  32769. idx[p] = idc;
  32770. idc += (l + closePathCorr);
  32771. }
  32772. // vertical distances (v)
  32773. var path1;
  32774. var path2;
  32775. var vertex1 = null;
  32776. var vertex2 = null;
  32777. for (i = 0; i < minlg + closePathCorr; i++) {
  32778. vTotalDistance[i] = 0;
  32779. vs[i] = [0];
  32780. for (p = 0; p < pathArray.length - 1; p++) {
  32781. path1 = pathArray[p];
  32782. path2 = pathArray[p + 1];
  32783. if (i === minlg) {
  32784. vertex1 = path1[0];
  32785. vertex2 = path2[0];
  32786. }
  32787. else {
  32788. vertex1 = path1[i];
  32789. vertex2 = path2[i];
  32790. }
  32791. vectlg = vertex2.subtract(vertex1).length();
  32792. dist = vectlg + vTotalDistance[i];
  32793. vs[i].push(dist);
  32794. vTotalDistance[i] = dist;
  32795. }
  32796. if (closeArray && vertex2 && vertex1) {
  32797. path1 = pathArray[p];
  32798. path2 = pathArray[0];
  32799. if (i === minlg) {
  32800. vertex2 = path2[0];
  32801. }
  32802. vectlg = vertex2.subtract(vertex1).length();
  32803. dist = vectlg + vTotalDistance[i];
  32804. vTotalDistance[i] = dist;
  32805. }
  32806. }
  32807. // uvs
  32808. var u;
  32809. var v;
  32810. if (customUV) {
  32811. for (p = 0; p < customUV.length; p++) {
  32812. uvs.push(customUV[p].x, customUV[p].y);
  32813. }
  32814. }
  32815. else {
  32816. for (p = 0; p < pathArray.length; p++) {
  32817. for (i = 0; i < minlg + closePathCorr; i++) {
  32818. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  32819. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  32820. if (invertUV) {
  32821. uvs.push(v, u);
  32822. }
  32823. else {
  32824. uvs.push(u, v);
  32825. }
  32826. }
  32827. }
  32828. }
  32829. // indices
  32830. p = 0; // path index
  32831. var pi = 0; // positions array index
  32832. var l1 = lg[p] - 1; // path1 length
  32833. var l2 = lg[p + 1] - 1; // path2 length
  32834. var min = (l1 < l2) ? l1 : l2; // current path stop index
  32835. var shft = idx[1] - idx[0]; // shift
  32836. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  32837. while (pi <= min && p < path1nb) {
  32838. // 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
  32839. indices.push(pi, pi + shft, pi + 1);
  32840. indices.push(pi + shft + 1, pi + 1, pi + shft);
  32841. pi += 1;
  32842. if (pi === min) {
  32843. p++;
  32844. if (p === lg.length - 1) {
  32845. shft = idx[0] - idx[p];
  32846. l1 = lg[p] - 1;
  32847. l2 = lg[0] - 1;
  32848. }
  32849. else {
  32850. shft = idx[p + 1] - idx[p];
  32851. l1 = lg[p] - 1;
  32852. l2 = lg[p + 1] - 1;
  32853. }
  32854. pi = idx[p];
  32855. min = (l1 < l2) ? l1 + pi : l2 + pi;
  32856. }
  32857. }
  32858. // normals
  32859. VertexData.ComputeNormals(positions, indices, normals);
  32860. if (closePath) {
  32861. var indexFirst = 0;
  32862. var indexLast = 0;
  32863. for (p = 0; p < pathArray.length; p++) {
  32864. indexFirst = idx[p] * 3;
  32865. if (p + 1 < pathArray.length) {
  32866. indexLast = (idx[p + 1] - 1) * 3;
  32867. }
  32868. else {
  32869. indexLast = normals.length - 3;
  32870. }
  32871. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  32872. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  32873. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  32874. normals[indexLast] = normals[indexFirst];
  32875. normals[indexLast + 1] = normals[indexFirst + 1];
  32876. normals[indexLast + 2] = normals[indexFirst + 2];
  32877. }
  32878. }
  32879. // sides
  32880. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32881. // Colors
  32882. var colors = null;
  32883. if (customColors) {
  32884. colors = new Float32Array(customColors.length * 4);
  32885. for (var c = 0; c < customColors.length; c++) {
  32886. colors[c * 4] = customColors[c].r;
  32887. colors[c * 4 + 1] = customColors[c].g;
  32888. colors[c * 4 + 2] = customColors[c].b;
  32889. colors[c * 4 + 3] = customColors[c].a;
  32890. }
  32891. }
  32892. // Result
  32893. var vertexData = new VertexData();
  32894. var positions32 = new Float32Array(positions);
  32895. var normals32 = new Float32Array(normals);
  32896. var uvs32 = new Float32Array(uvs);
  32897. vertexData.indices = indices;
  32898. vertexData.positions = positions32;
  32899. vertexData.normals = normals32;
  32900. vertexData.uvs = uvs32;
  32901. if (colors) {
  32902. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  32903. }
  32904. if (closePath) {
  32905. vertexData._idx = idx;
  32906. }
  32907. return vertexData;
  32908. };
  32909. /**
  32910. * Creates the VertexData of the Box.
  32911. */
  32912. VertexData.CreateBox = function (options) {
  32913. var normalsSource = [
  32914. new BABYLON.Vector3(0, 0, 1),
  32915. new BABYLON.Vector3(0, 0, -1),
  32916. new BABYLON.Vector3(1, 0, 0),
  32917. new BABYLON.Vector3(-1, 0, 0),
  32918. new BABYLON.Vector3(0, 1, 0),
  32919. new BABYLON.Vector3(0, -1, 0)
  32920. ];
  32921. var indices = [];
  32922. var positions = [];
  32923. var normals = [];
  32924. var uvs = [];
  32925. var width = options.width || options.size || 1;
  32926. var height = options.height || options.size || 1;
  32927. var depth = options.depth || options.size || 1;
  32928. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32929. var faceUV = options.faceUV || new Array(6);
  32930. var faceColors = options.faceColors;
  32931. var colors = [];
  32932. // default face colors and UV if undefined
  32933. for (var f = 0; f < 6; f++) {
  32934. if (faceUV[f] === undefined) {
  32935. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32936. }
  32937. if (faceColors && faceColors[f] === undefined) {
  32938. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32939. }
  32940. }
  32941. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  32942. // Create each face in turn.
  32943. for (var index = 0; index < normalsSource.length; index++) {
  32944. var normal = normalsSource[index];
  32945. // Get two vectors perpendicular to the face normal and to each other.
  32946. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  32947. var side2 = BABYLON.Vector3.Cross(normal, side1);
  32948. // Six indices (two triangles) per face.
  32949. var verticesLength = positions.length / 3;
  32950. indices.push(verticesLength);
  32951. indices.push(verticesLength + 1);
  32952. indices.push(verticesLength + 2);
  32953. indices.push(verticesLength);
  32954. indices.push(verticesLength + 2);
  32955. indices.push(verticesLength + 3);
  32956. // Four vertices per face.
  32957. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  32958. positions.push(vertex.x, vertex.y, vertex.z);
  32959. normals.push(normal.x, normal.y, normal.z);
  32960. uvs.push(faceUV[index].z, faceUV[index].w);
  32961. if (faceColors) {
  32962. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32963. }
  32964. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  32965. positions.push(vertex.x, vertex.y, vertex.z);
  32966. normals.push(normal.x, normal.y, normal.z);
  32967. uvs.push(faceUV[index].x, faceUV[index].w);
  32968. if (faceColors) {
  32969. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32970. }
  32971. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  32972. positions.push(vertex.x, vertex.y, vertex.z);
  32973. normals.push(normal.x, normal.y, normal.z);
  32974. uvs.push(faceUV[index].x, faceUV[index].y);
  32975. if (faceColors) {
  32976. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32977. }
  32978. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  32979. positions.push(vertex.x, vertex.y, vertex.z);
  32980. normals.push(normal.x, normal.y, normal.z);
  32981. uvs.push(faceUV[index].z, faceUV[index].y);
  32982. if (faceColors) {
  32983. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32984. }
  32985. }
  32986. // sides
  32987. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32988. // Result
  32989. var vertexData = new VertexData();
  32990. vertexData.indices = indices;
  32991. vertexData.positions = positions;
  32992. vertexData.normals = normals;
  32993. vertexData.uvs = uvs;
  32994. if (faceColors) {
  32995. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  32996. vertexData.colors = totalColors;
  32997. }
  32998. return vertexData;
  32999. };
  33000. /**
  33001. * Creates the VertexData of the Sphere.
  33002. */
  33003. VertexData.CreateSphere = function (options) {
  33004. var segments = options.segments || 32;
  33005. var diameterX = options.diameterX || options.diameter || 1;
  33006. var diameterY = options.diameterY || options.diameter || 1;
  33007. var diameterZ = options.diameterZ || options.diameter || 1;
  33008. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33009. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33010. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33011. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33012. var totalZRotationSteps = 2 + segments;
  33013. var totalYRotationSteps = 2 * totalZRotationSteps;
  33014. var indices = [];
  33015. var positions = [];
  33016. var normals = [];
  33017. var uvs = [];
  33018. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33019. var normalizedZ = zRotationStep / totalZRotationSteps;
  33020. var angleZ = normalizedZ * Math.PI * slice;
  33021. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33022. var normalizedY = yRotationStep / totalYRotationSteps;
  33023. var angleY = normalizedY * Math.PI * 2 * arc;
  33024. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33025. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33026. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33027. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33028. var vertex = complete.multiply(radius);
  33029. var normal = complete.divide(radius).normalize();
  33030. positions.push(vertex.x, vertex.y, vertex.z);
  33031. normals.push(normal.x, normal.y, normal.z);
  33032. uvs.push(normalizedY, normalizedZ);
  33033. }
  33034. if (zRotationStep > 0) {
  33035. var verticesCount = positions.length / 3;
  33036. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33037. indices.push((firstIndex));
  33038. indices.push((firstIndex + 1));
  33039. indices.push(firstIndex + totalYRotationSteps + 1);
  33040. indices.push((firstIndex + totalYRotationSteps + 1));
  33041. indices.push((firstIndex + 1));
  33042. indices.push((firstIndex + totalYRotationSteps + 2));
  33043. }
  33044. }
  33045. }
  33046. // Sides
  33047. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33048. // Result
  33049. var vertexData = new VertexData();
  33050. vertexData.indices = indices;
  33051. vertexData.positions = positions;
  33052. vertexData.normals = normals;
  33053. vertexData.uvs = uvs;
  33054. return vertexData;
  33055. };
  33056. /**
  33057. * Creates the VertexData of the Cylinder or Cone.
  33058. */
  33059. VertexData.CreateCylinder = function (options) {
  33060. var height = options.height || 2;
  33061. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33062. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33063. var tessellation = options.tessellation || 24;
  33064. var subdivisions = options.subdivisions || 1;
  33065. var hasRings = options.hasRings ? true : false;
  33066. var enclose = options.enclose ? true : false;
  33067. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33068. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33069. var faceUV = options.faceUV || new Array(3);
  33070. var faceColors = options.faceColors;
  33071. // default face colors and UV if undefined
  33072. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33073. var ringNb = (hasRings) ? subdivisions : 1;
  33074. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33075. var f;
  33076. for (f = 0; f < surfaceNb; f++) {
  33077. if (faceColors && faceColors[f] === undefined) {
  33078. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33079. }
  33080. }
  33081. for (f = 0; f < surfaceNb; f++) {
  33082. if (faceUV && faceUV[f] === undefined) {
  33083. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33084. }
  33085. }
  33086. var indices = new Array();
  33087. var positions = new Array();
  33088. var normals = new Array();
  33089. var uvs = new Array();
  33090. var colors = new Array();
  33091. var angle_step = Math.PI * 2 * arc / tessellation;
  33092. var angle;
  33093. var h;
  33094. var radius;
  33095. var tan = (diameterBottom - diameterTop) / 2 / height;
  33096. var ringVertex = BABYLON.Vector3.Zero();
  33097. var ringNormal = BABYLON.Vector3.Zero();
  33098. var ringFirstVertex = BABYLON.Vector3.Zero();
  33099. var ringFirstNormal = BABYLON.Vector3.Zero();
  33100. var quadNormal = BABYLON.Vector3.Zero();
  33101. var Y = BABYLON.Axis.Y;
  33102. // positions, normals, uvs
  33103. var i;
  33104. var j;
  33105. var r;
  33106. var ringIdx = 1;
  33107. var s = 1; // surface index
  33108. var cs = 0;
  33109. var v = 0;
  33110. for (i = 0; i <= subdivisions; i++) {
  33111. h = i / subdivisions;
  33112. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33113. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33114. for (r = 0; r < ringIdx; r++) {
  33115. if (hasRings) {
  33116. s += r;
  33117. }
  33118. if (enclose) {
  33119. s += 2 * r;
  33120. }
  33121. for (j = 0; j <= tessellation; j++) {
  33122. angle = j * angle_step;
  33123. // position
  33124. ringVertex.x = Math.cos(-angle) * radius;
  33125. ringVertex.y = -height / 2 + h * height;
  33126. ringVertex.z = Math.sin(-angle) * radius;
  33127. // normal
  33128. if (diameterTop === 0 && i === subdivisions) {
  33129. // if no top cap, reuse former normals
  33130. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33131. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33132. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33133. }
  33134. else {
  33135. ringNormal.x = ringVertex.x;
  33136. ringNormal.z = ringVertex.z;
  33137. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33138. ringNormal.normalize();
  33139. }
  33140. // keep first ring vertex values for enclose
  33141. if (j === 0) {
  33142. ringFirstVertex.copyFrom(ringVertex);
  33143. ringFirstNormal.copyFrom(ringNormal);
  33144. }
  33145. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33146. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33147. if (hasRings) {
  33148. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33149. }
  33150. else {
  33151. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33152. }
  33153. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33154. if (faceColors) {
  33155. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33156. }
  33157. }
  33158. // if enclose, add four vertices and their dedicated normals
  33159. if (arc !== 1 && enclose) {
  33160. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33161. positions.push(0, ringVertex.y, 0);
  33162. positions.push(0, ringVertex.y, 0);
  33163. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33164. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33165. quadNormal.normalize();
  33166. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33167. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33168. quadNormal.normalize();
  33169. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33170. if (hasRings) {
  33171. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33172. }
  33173. else {
  33174. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33175. }
  33176. uvs.push(faceUV[s + 1].x, v);
  33177. uvs.push(faceUV[s + 1].z, v);
  33178. if (hasRings) {
  33179. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33180. }
  33181. else {
  33182. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33183. }
  33184. uvs.push(faceUV[s + 2].x, v);
  33185. uvs.push(faceUV[s + 2].z, v);
  33186. if (faceColors) {
  33187. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33188. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33189. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33190. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33191. }
  33192. }
  33193. if (cs !== s) {
  33194. cs = s;
  33195. }
  33196. }
  33197. }
  33198. // indices
  33199. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33200. var s;
  33201. i = 0;
  33202. for (s = 0; s < subdivisions; s++) {
  33203. var i0 = 0;
  33204. var i1 = 0;
  33205. var i2 = 0;
  33206. var i3 = 0;
  33207. for (j = 0; j < tessellation; j++) {
  33208. i0 = i * (e + 1) + j;
  33209. i1 = (i + 1) * (e + 1) + j;
  33210. i2 = i * (e + 1) + (j + 1);
  33211. i3 = (i + 1) * (e + 1) + (j + 1);
  33212. indices.push(i0, i1, i2);
  33213. indices.push(i3, i2, i1);
  33214. }
  33215. if (arc !== 1 && enclose) {
  33216. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33217. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33218. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33219. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33220. }
  33221. i = (hasRings) ? (i + 2) : (i + 1);
  33222. }
  33223. // Caps
  33224. var createCylinderCap = function (isTop) {
  33225. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33226. if (radius === 0) {
  33227. return;
  33228. }
  33229. // Cap positions, normals & uvs
  33230. var angle;
  33231. var circleVector;
  33232. var i;
  33233. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33234. var c = null;
  33235. if (faceColors) {
  33236. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33237. }
  33238. // cap center
  33239. var vbase = positions.length / 3;
  33240. var offset = isTop ? height / 2 : -height / 2;
  33241. var center = new BABYLON.Vector3(0, offset, 0);
  33242. positions.push(center.x, center.y, center.z);
  33243. normals.push(0, isTop ? 1 : -1, 0);
  33244. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33245. if (c) {
  33246. colors.push(c.r, c.g, c.b, c.a);
  33247. }
  33248. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33249. for (i = 0; i <= tessellation; i++) {
  33250. angle = Math.PI * 2 * i * arc / tessellation;
  33251. var cos = Math.cos(-angle);
  33252. var sin = Math.sin(-angle);
  33253. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33254. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33255. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33256. normals.push(0, isTop ? 1 : -1, 0);
  33257. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33258. if (c) {
  33259. colors.push(c.r, c.g, c.b, c.a);
  33260. }
  33261. }
  33262. // Cap indices
  33263. for (i = 0; i < tessellation; i++) {
  33264. if (!isTop) {
  33265. indices.push(vbase);
  33266. indices.push(vbase + (i + 1));
  33267. indices.push(vbase + (i + 2));
  33268. }
  33269. else {
  33270. indices.push(vbase);
  33271. indices.push(vbase + (i + 2));
  33272. indices.push(vbase + (i + 1));
  33273. }
  33274. }
  33275. };
  33276. // add caps to geometry
  33277. createCylinderCap(false);
  33278. createCylinderCap(true);
  33279. // Sides
  33280. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33281. var vertexData = new VertexData();
  33282. vertexData.indices = indices;
  33283. vertexData.positions = positions;
  33284. vertexData.normals = normals;
  33285. vertexData.uvs = uvs;
  33286. if (faceColors) {
  33287. vertexData.colors = colors;
  33288. }
  33289. return vertexData;
  33290. };
  33291. /**
  33292. * Creates the VertexData of the Torus.
  33293. */
  33294. VertexData.CreateTorus = function (options) {
  33295. var indices = [];
  33296. var positions = [];
  33297. var normals = [];
  33298. var uvs = [];
  33299. var diameter = options.diameter || 1;
  33300. var thickness = options.thickness || 0.5;
  33301. var tessellation = options.tessellation || 16;
  33302. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33303. var stride = tessellation + 1;
  33304. for (var i = 0; i <= tessellation; i++) {
  33305. var u = i / tessellation;
  33306. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33307. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33308. for (var j = 0; j <= tessellation; j++) {
  33309. var v = 1 - j / tessellation;
  33310. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33311. var dx = Math.cos(innerAngle);
  33312. var dy = Math.sin(innerAngle);
  33313. // Create a vertex.
  33314. var normal = new BABYLON.Vector3(dx, dy, 0);
  33315. var position = normal.scale(thickness / 2);
  33316. var textureCoordinate = new BABYLON.Vector2(u, v);
  33317. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33318. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33319. positions.push(position.x, position.y, position.z);
  33320. normals.push(normal.x, normal.y, normal.z);
  33321. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33322. // And create indices for two triangles.
  33323. var nextI = (i + 1) % stride;
  33324. var nextJ = (j + 1) % stride;
  33325. indices.push(i * stride + j);
  33326. indices.push(i * stride + nextJ);
  33327. indices.push(nextI * stride + j);
  33328. indices.push(i * stride + nextJ);
  33329. indices.push(nextI * stride + nextJ);
  33330. indices.push(nextI * stride + j);
  33331. }
  33332. }
  33333. // Sides
  33334. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33335. // Result
  33336. var vertexData = new VertexData();
  33337. vertexData.indices = indices;
  33338. vertexData.positions = positions;
  33339. vertexData.normals = normals;
  33340. vertexData.uvs = uvs;
  33341. return vertexData;
  33342. };
  33343. /**
  33344. * Creates the VertexData of the LineSystem.
  33345. */
  33346. VertexData.CreateLineSystem = function (options) {
  33347. var indices = [];
  33348. var positions = [];
  33349. var lines = options.lines;
  33350. var colors = options.colors;
  33351. var vertexColors = [];
  33352. var idx = 0;
  33353. for (var l = 0; l < lines.length; l++) {
  33354. var points = lines[l];
  33355. for (var index = 0; index < points.length; index++) {
  33356. positions.push(points[index].x, points[index].y, points[index].z);
  33357. if (colors) {
  33358. var color = colors[l];
  33359. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  33360. }
  33361. if (index > 0) {
  33362. indices.push(idx - 1);
  33363. indices.push(idx);
  33364. }
  33365. idx++;
  33366. }
  33367. }
  33368. var vertexData = new VertexData();
  33369. vertexData.indices = indices;
  33370. vertexData.positions = positions;
  33371. if (colors) {
  33372. vertexData.colors = vertexColors;
  33373. }
  33374. return vertexData;
  33375. };
  33376. /**
  33377. * Create the VertexData of the DashedLines.
  33378. */
  33379. VertexData.CreateDashedLines = function (options) {
  33380. var dashSize = options.dashSize || 3;
  33381. var gapSize = options.gapSize || 1;
  33382. var dashNb = options.dashNb || 200;
  33383. var points = options.points;
  33384. var positions = new Array();
  33385. var indices = new Array();
  33386. var curvect = BABYLON.Vector3.Zero();
  33387. var lg = 0;
  33388. var nb = 0;
  33389. var shft = 0;
  33390. var dashshft = 0;
  33391. var curshft = 0;
  33392. var idx = 0;
  33393. var i = 0;
  33394. for (i = 0; i < points.length - 1; i++) {
  33395. points[i + 1].subtractToRef(points[i], curvect);
  33396. lg += curvect.length();
  33397. }
  33398. shft = lg / dashNb;
  33399. dashshft = dashSize * shft / (dashSize + gapSize);
  33400. for (i = 0; i < points.length - 1; i++) {
  33401. points[i + 1].subtractToRef(points[i], curvect);
  33402. nb = Math.floor(curvect.length() / shft);
  33403. curvect.normalize();
  33404. for (var j = 0; j < nb; j++) {
  33405. curshft = shft * j;
  33406. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  33407. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  33408. indices.push(idx, idx + 1);
  33409. idx += 2;
  33410. }
  33411. }
  33412. // Result
  33413. var vertexData = new VertexData();
  33414. vertexData.positions = positions;
  33415. vertexData.indices = indices;
  33416. return vertexData;
  33417. };
  33418. /**
  33419. * Creates the VertexData of the Ground.
  33420. */
  33421. VertexData.CreateGround = function (options) {
  33422. var indices = [];
  33423. var positions = [];
  33424. var normals = [];
  33425. var uvs = [];
  33426. var row, col;
  33427. var width = options.width || 1;
  33428. var height = options.height || 1;
  33429. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  33430. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  33431. for (row = 0; row <= subdivisionsY; row++) {
  33432. for (col = 0; col <= subdivisionsX; col++) {
  33433. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  33434. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33435. positions.push(position.x, position.y, position.z);
  33436. normals.push(normal.x, normal.y, normal.z);
  33437. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  33438. }
  33439. }
  33440. for (row = 0; row < subdivisionsY; row++) {
  33441. for (col = 0; col < subdivisionsX; col++) {
  33442. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33443. indices.push(col + 1 + row * (subdivisionsX + 1));
  33444. indices.push(col + row * (subdivisionsX + 1));
  33445. indices.push(col + (row + 1) * (subdivisionsX + 1));
  33446. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33447. indices.push(col + row * (subdivisionsX + 1));
  33448. }
  33449. }
  33450. // Result
  33451. var vertexData = new VertexData();
  33452. vertexData.indices = indices;
  33453. vertexData.positions = positions;
  33454. vertexData.normals = normals;
  33455. vertexData.uvs = uvs;
  33456. return vertexData;
  33457. };
  33458. /**
  33459. * Creates the VertexData of the TiledGround.
  33460. */
  33461. VertexData.CreateTiledGround = function (options) {
  33462. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  33463. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  33464. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  33465. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  33466. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  33467. var precision = options.precision || { w: 1, h: 1 };
  33468. var indices = new Array();
  33469. var positions = new Array();
  33470. var normals = new Array();
  33471. var uvs = new Array();
  33472. var row, col, tileRow, tileCol;
  33473. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  33474. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  33475. precision.w = (precision.w < 1) ? 1 : precision.w;
  33476. precision.h = (precision.h < 1) ? 1 : precision.h;
  33477. var tileSize = {
  33478. 'w': (xmax - xmin) / subdivisions.w,
  33479. 'h': (zmax - zmin) / subdivisions.h
  33480. };
  33481. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  33482. // Indices
  33483. var base = positions.length / 3;
  33484. var rowLength = precision.w + 1;
  33485. for (row = 0; row < precision.h; row++) {
  33486. for (col = 0; col < precision.w; col++) {
  33487. var square = [
  33488. base + col + row * rowLength,
  33489. base + (col + 1) + row * rowLength,
  33490. base + (col + 1) + (row + 1) * rowLength,
  33491. base + col + (row + 1) * rowLength
  33492. ];
  33493. indices.push(square[1]);
  33494. indices.push(square[2]);
  33495. indices.push(square[3]);
  33496. indices.push(square[0]);
  33497. indices.push(square[1]);
  33498. indices.push(square[3]);
  33499. }
  33500. }
  33501. // Position, normals and uvs
  33502. var position = BABYLON.Vector3.Zero();
  33503. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33504. for (row = 0; row <= precision.h; row++) {
  33505. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33506. for (col = 0; col <= precision.w; col++) {
  33507. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33508. position.y = 0;
  33509. positions.push(position.x, position.y, position.z);
  33510. normals.push(normal.x, normal.y, normal.z);
  33511. uvs.push(col / precision.w, row / precision.h);
  33512. }
  33513. }
  33514. }
  33515. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33516. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33517. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33518. }
  33519. }
  33520. // Result
  33521. var vertexData = new VertexData();
  33522. vertexData.indices = indices;
  33523. vertexData.positions = positions;
  33524. vertexData.normals = normals;
  33525. vertexData.uvs = uvs;
  33526. return vertexData;
  33527. };
  33528. /**
  33529. * Creates the VertexData of the Ground designed from a heightmap.
  33530. */
  33531. VertexData.CreateGroundFromHeightMap = function (options) {
  33532. var indices = [];
  33533. var positions = [];
  33534. var normals = [];
  33535. var uvs = [];
  33536. var row, col;
  33537. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  33538. // Vertices
  33539. for (row = 0; row <= options.subdivisions; row++) {
  33540. for (col = 0; col <= options.subdivisions; col++) {
  33541. 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));
  33542. // Compute height
  33543. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33544. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33545. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33546. var r = options.buffer[pos] / 255.0;
  33547. var g = options.buffer[pos + 1] / 255.0;
  33548. var b = options.buffer[pos + 2] / 255.0;
  33549. var gradient = r * filter.r + g * filter.g + b * filter.b;
  33550. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33551. // Add vertex
  33552. positions.push(position.x, position.y, position.z);
  33553. normals.push(0, 0, 0);
  33554. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33555. }
  33556. }
  33557. // Indices
  33558. for (row = 0; row < options.subdivisions; row++) {
  33559. for (col = 0; col < options.subdivisions; col++) {
  33560. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33561. indices.push(col + 1 + row * (options.subdivisions + 1));
  33562. indices.push(col + row * (options.subdivisions + 1));
  33563. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33564. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33565. indices.push(col + row * (options.subdivisions + 1));
  33566. }
  33567. }
  33568. // Normals
  33569. VertexData.ComputeNormals(positions, indices, normals);
  33570. // Result
  33571. var vertexData = new VertexData();
  33572. vertexData.indices = indices;
  33573. vertexData.positions = positions;
  33574. vertexData.normals = normals;
  33575. vertexData.uvs = uvs;
  33576. return vertexData;
  33577. };
  33578. /**
  33579. * Creates the VertexData of the Plane.
  33580. */
  33581. VertexData.CreatePlane = function (options) {
  33582. var indices = [];
  33583. var positions = [];
  33584. var normals = [];
  33585. var uvs = [];
  33586. var width = options.width || options.size || 1;
  33587. var height = options.height || options.size || 1;
  33588. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33589. // Vertices
  33590. var halfWidth = width / 2.0;
  33591. var halfHeight = height / 2.0;
  33592. positions.push(-halfWidth, -halfHeight, 0);
  33593. normals.push(0, 0, -1.0);
  33594. uvs.push(0.0, 0.0);
  33595. positions.push(halfWidth, -halfHeight, 0);
  33596. normals.push(0, 0, -1.0);
  33597. uvs.push(1.0, 0.0);
  33598. positions.push(halfWidth, halfHeight, 0);
  33599. normals.push(0, 0, -1.0);
  33600. uvs.push(1.0, 1.0);
  33601. positions.push(-halfWidth, halfHeight, 0);
  33602. normals.push(0, 0, -1.0);
  33603. uvs.push(0.0, 1.0);
  33604. // Indices
  33605. indices.push(0);
  33606. indices.push(1);
  33607. indices.push(2);
  33608. indices.push(0);
  33609. indices.push(2);
  33610. indices.push(3);
  33611. // Sides
  33612. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33613. // Result
  33614. var vertexData = new VertexData();
  33615. vertexData.indices = indices;
  33616. vertexData.positions = positions;
  33617. vertexData.normals = normals;
  33618. vertexData.uvs = uvs;
  33619. return vertexData;
  33620. };
  33621. /**
  33622. * Creates the VertexData of the Disc or regular Polygon.
  33623. */
  33624. VertexData.CreateDisc = function (options) {
  33625. var positions = new Array();
  33626. var indices = new Array();
  33627. var normals = new Array();
  33628. var uvs = new Array();
  33629. var radius = options.radius || 0.5;
  33630. var tessellation = options.tessellation || 64;
  33631. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33632. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33633. // positions and uvs
  33634. positions.push(0, 0, 0); // disc center first
  33635. uvs.push(0.5, 0.5);
  33636. var theta = Math.PI * 2 * arc;
  33637. var step = theta / tessellation;
  33638. for (var a = 0; a < theta; a += step) {
  33639. var x = Math.cos(a);
  33640. var y = Math.sin(a);
  33641. var u = (x + 1) / 2;
  33642. var v = (1 - y) / 2;
  33643. positions.push(radius * x, radius * y, 0);
  33644. uvs.push(u, v);
  33645. }
  33646. if (arc === 1) {
  33647. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33648. uvs.push(uvs[2], uvs[3]);
  33649. }
  33650. //indices
  33651. var vertexNb = positions.length / 3;
  33652. for (var i = 1; i < vertexNb - 1; i++) {
  33653. indices.push(i + 1, 0, i);
  33654. }
  33655. // result
  33656. VertexData.ComputeNormals(positions, indices, normals);
  33657. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33658. var vertexData = new VertexData();
  33659. vertexData.indices = indices;
  33660. vertexData.positions = positions;
  33661. vertexData.normals = normals;
  33662. vertexData.uvs = uvs;
  33663. return vertexData;
  33664. };
  33665. /**
  33666. * Re-creates the VertexData of the Polygon for sideOrientation.
  33667. */
  33668. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  33669. var faceUV = fUV || new Array(3);
  33670. var faceColors = fColors;
  33671. var colors = [];
  33672. // default face colors and UV if undefined
  33673. for (var f = 0; f < 3; f++) {
  33674. if (faceUV[f] === undefined) {
  33675. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33676. }
  33677. if (faceColors && faceColors[f] === undefined) {
  33678. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33679. }
  33680. }
  33681. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33682. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33683. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33684. var indices = polygon.getIndices();
  33685. // set face colours and textures
  33686. var idx = 0;
  33687. var face = 0;
  33688. for (var index = 0; index < normals.length; index += 3) {
  33689. //Edge Face no. 1
  33690. if (Math.abs(normals[index + 1]) < 0.001) {
  33691. face = 1;
  33692. }
  33693. //Top Face no. 0
  33694. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  33695. face = 0;
  33696. }
  33697. //Bottom Face no. 2
  33698. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  33699. face = 2;
  33700. }
  33701. idx = index / 3;
  33702. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  33703. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  33704. if (faceColors) {
  33705. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  33706. }
  33707. }
  33708. // sides
  33709. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  33710. // Result
  33711. var vertexData = new VertexData();
  33712. vertexData.indices = indices;
  33713. vertexData.positions = positions;
  33714. vertexData.normals = normals;
  33715. vertexData.uvs = uvs;
  33716. if (faceColors) {
  33717. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33718. vertexData.colors = totalColors;
  33719. }
  33720. return vertexData;
  33721. };
  33722. /**
  33723. * Creates the VertexData of the IcoSphere.
  33724. */
  33725. VertexData.CreateIcoSphere = function (options) {
  33726. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33727. var radius = options.radius || 1;
  33728. var flat = (options.flat === undefined) ? true : options.flat;
  33729. var subdivisions = options.subdivisions || 4;
  33730. var radiusX = options.radiusX || radius;
  33731. var radiusY = options.radiusY || radius;
  33732. var radiusZ = options.radiusZ || radius;
  33733. var t = (1 + Math.sqrt(5)) / 2;
  33734. // 12 vertex x,y,z
  33735. var ico_vertices = [
  33736. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33737. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33738. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33739. ];
  33740. // index of 3 vertex makes a face of icopshere
  33741. var ico_indices = [
  33742. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33743. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33744. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33745. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33746. ];
  33747. // vertex for uv have aliased position, not for UV
  33748. var vertices_unalias_id = [
  33749. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33750. // vertex alias
  33751. 0,
  33752. 2,
  33753. 3,
  33754. 3,
  33755. 3,
  33756. 4,
  33757. 7,
  33758. 8,
  33759. 9,
  33760. 9,
  33761. 10,
  33762. 11 // 23: B + 12
  33763. ];
  33764. // uv as integer step (not pixels !)
  33765. var ico_vertexuv = [
  33766. 5, 1, 3, 1, 6, 4, 0, 0,
  33767. 5, 3, 4, 2, 2, 2, 4, 0,
  33768. 2, 0, 1, 1, 6, 0, 6, 2,
  33769. // vertex alias (for same vertex on different faces)
  33770. 0, 4,
  33771. 3, 3,
  33772. 4, 4,
  33773. 3, 1,
  33774. 4, 2,
  33775. 4, 4,
  33776. 0, 2,
  33777. 1, 1,
  33778. 2, 2,
  33779. 3, 3,
  33780. 1, 3,
  33781. 2, 4 // 23: B + 12
  33782. ];
  33783. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33784. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33785. // First island of uv mapping
  33786. // v = 4h 3+ 2
  33787. // v = 3h 9+ 4
  33788. // v = 2h 9+ 5 B
  33789. // v = 1h 9 1 0
  33790. // v = 0h 3 8 7 A
  33791. // u = 0 1 2 3 4 5 6 *a
  33792. // Second island of uv mapping
  33793. // v = 4h 0+ B+ 4+
  33794. // v = 3h A+ 2+
  33795. // v = 2h 7+ 6 3+
  33796. // v = 1h 8+ 3+
  33797. // v = 0h
  33798. // u = 0 1 2 3 4 5 6 *a
  33799. // Face layout on texture UV mapping
  33800. // ============
  33801. // \ 4 /\ 16 / ======
  33802. // \ / \ / /\ 11 /
  33803. // \/ 7 \/ / \ /
  33804. // ======= / 10 \/
  33805. // /\ 17 /\ =======
  33806. // / \ / \ \ 15 /\
  33807. // / 8 \/ 12 \ \ / \
  33808. // ============ \/ 6 \
  33809. // \ 18 /\ ============
  33810. // \ / \ \ 5 /\ 0 /
  33811. // \/ 13 \ \ / \ /
  33812. // ======= \/ 1 \/
  33813. // =============
  33814. // /\ 19 /\ 2 /\
  33815. // / \ / \ / \
  33816. // / 14 \/ 9 \/ 3 \
  33817. // ===================
  33818. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  33819. var ustep = 138 / 1024;
  33820. var vstep = 239 / 1024;
  33821. var uoffset = 60 / 1024;
  33822. var voffset = 26 / 1024;
  33823. // Second island should have margin, not to touch the first island
  33824. // avoid any borderline artefact in pixel rounding
  33825. var island_u_offset = -40 / 1024;
  33826. var island_v_offset = +20 / 1024;
  33827. // face is either island 0 or 1 :
  33828. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  33829. var island = [
  33830. 0, 0, 0, 0, 1,
  33831. 0, 0, 1, 1, 0,
  33832. 0, 0, 1, 1, 0,
  33833. 0, 1, 1, 1, 0 // 15 - 19
  33834. ];
  33835. var indices = new Array();
  33836. var positions = new Array();
  33837. var normals = new Array();
  33838. var uvs = new Array();
  33839. var current_indice = 0;
  33840. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  33841. var face_vertex_pos = new Array(3);
  33842. var face_vertex_uv = new Array(3);
  33843. var v012;
  33844. for (v012 = 0; v012 < 3; v012++) {
  33845. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  33846. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  33847. }
  33848. // create all with normals
  33849. for (var face = 0; face < 20; face++) {
  33850. // 3 vertex per face
  33851. for (v012 = 0; v012 < 3; v012++) {
  33852. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  33853. var v_id = ico_indices[3 * face + v012];
  33854. // vertex have 3D position (x,y,z)
  33855. 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]);
  33856. // Normalize to get normal, then scale to radius
  33857. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  33858. // uv Coordinates from vertex ID
  33859. 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);
  33860. }
  33861. // Subdivide the face (interpolate pos, norm, uv)
  33862. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  33863. // - norm is linear interpolation of vertex corner normal
  33864. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  33865. // - uv is linear interpolation
  33866. //
  33867. // Topology is as below for sub-divide by 2
  33868. // vertex shown as v0,v1,v2
  33869. // interp index is i1 to progress in range [v0,v1[
  33870. // interp index is i2 to progress in range [v0,v2[
  33871. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  33872. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33873. //
  33874. //
  33875. // i2 v2
  33876. // ^ ^
  33877. // / / \
  33878. // / / \
  33879. // / / \
  33880. // / / (0,1) \
  33881. // / #---------\
  33882. // / / \ (0,0)'/ \
  33883. // / / \ / \
  33884. // / / \ / \
  33885. // / / (0,0) \ / (1,0) \
  33886. // / #---------#---------\
  33887. // v0 v1
  33888. //
  33889. // --------------------> i1
  33890. //
  33891. // interp of (i1,i2):
  33892. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  33893. // along i1 : lerp(x0,x1, i1/(S-i2))
  33894. //
  33895. // centroid of triangle is needed to get help normal computation
  33896. // (c1,c2) are used for centroid location
  33897. var interp_vertex = function (i1, i2, c1, c2) {
  33898. // vertex is interpolated from
  33899. // - face_vertex_pos[0..2]
  33900. // - face_vertex_uv[0..2]
  33901. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  33902. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  33903. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  33904. pos_interp.normalize();
  33905. var vertex_normal;
  33906. if (flat) {
  33907. // in flat mode, recalculate normal as face centroid normal
  33908. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  33909. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  33910. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  33911. }
  33912. else {
  33913. // in smooth mode, recalculate normal from each single vertex position
  33914. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  33915. }
  33916. // Vertex normal need correction due to X,Y,Z radius scaling
  33917. vertex_normal.x /= radiusX;
  33918. vertex_normal.y /= radiusY;
  33919. vertex_normal.z /= radiusZ;
  33920. vertex_normal.normalize();
  33921. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  33922. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  33923. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  33924. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  33925. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  33926. uvs.push(uv_interp.x, uv_interp.y);
  33927. // push each vertex has member of a face
  33928. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  33929. indices.push(current_indice);
  33930. current_indice++;
  33931. };
  33932. for (var i2 = 0; i2 < subdivisions; i2++) {
  33933. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  33934. // face : (i1,i2) for /\ :
  33935. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  33936. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33937. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33938. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33939. if (i1 + i2 + 1 < subdivisions) {
  33940. // face : (i1,i2)' for \/ :
  33941. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33942. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33943. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33944. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33945. }
  33946. }
  33947. }
  33948. }
  33949. // Sides
  33950. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33951. // Result
  33952. var vertexData = new VertexData();
  33953. vertexData.indices = indices;
  33954. vertexData.positions = positions;
  33955. vertexData.normals = normals;
  33956. vertexData.uvs = uvs;
  33957. return vertexData;
  33958. };
  33959. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  33960. /**
  33961. * Creates the VertexData of the Polyhedron.
  33962. */
  33963. VertexData.CreatePolyhedron = function (options) {
  33964. // provided polyhedron types :
  33965. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  33966. // 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)
  33967. var polyhedra = [];
  33968. 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]] };
  33969. 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]] };
  33970. polyhedra[2] = {
  33971. 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]],
  33972. 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]]
  33973. };
  33974. polyhedra[3] = {
  33975. 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]],
  33976. 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]]
  33977. };
  33978. polyhedra[4] = {
  33979. 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]],
  33980. 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]]
  33981. };
  33982. 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]] };
  33983. 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]] };
  33984. 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]] };
  33985. 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]] };
  33986. 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]] };
  33987. 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]] };
  33988. 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]] };
  33989. 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]] };
  33990. 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]] };
  33991. polyhedra[14] = {
  33992. 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]],
  33993. 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]]
  33994. };
  33995. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  33996. var size = options.size;
  33997. var sizeX = options.sizeX || size || 1;
  33998. var sizeY = options.sizeY || size || 1;
  33999. var sizeZ = options.sizeZ || size || 1;
  34000. var data = options.custom || polyhedra[type];
  34001. var nbfaces = data.face.length;
  34002. var faceUV = options.faceUV || new Array(nbfaces);
  34003. var faceColors = options.faceColors;
  34004. var flat = (options.flat === undefined) ? true : options.flat;
  34005. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34006. var positions = new Array();
  34007. var indices = new Array();
  34008. var normals = new Array();
  34009. var uvs = new Array();
  34010. var colors = new Array();
  34011. var index = 0;
  34012. var faceIdx = 0; // face cursor in the array "indexes"
  34013. var indexes = new Array();
  34014. var i = 0;
  34015. var f = 0;
  34016. var u, v, ang, x, y, tmp;
  34017. // default face colors and UV if undefined
  34018. if (flat) {
  34019. for (f = 0; f < nbfaces; f++) {
  34020. if (faceColors && faceColors[f] === undefined) {
  34021. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34022. }
  34023. if (faceUV && faceUV[f] === undefined) {
  34024. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34025. }
  34026. }
  34027. }
  34028. if (!flat) {
  34029. for (i = 0; i < data.vertex.length; i++) {
  34030. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34031. uvs.push(0, 0);
  34032. }
  34033. for (f = 0; f < nbfaces; f++) {
  34034. for (i = 0; i < data.face[f].length - 2; i++) {
  34035. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34036. }
  34037. }
  34038. }
  34039. else {
  34040. for (f = 0; f < nbfaces; f++) {
  34041. var fl = data.face[f].length; // number of vertices of the current face
  34042. ang = 2 * Math.PI / fl;
  34043. x = 0.5 * Math.tan(ang / 2);
  34044. y = 0.5;
  34045. // positions, uvs, colors
  34046. for (i = 0; i < fl; i++) {
  34047. // positions
  34048. 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);
  34049. indexes.push(index);
  34050. index++;
  34051. // uvs
  34052. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34053. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34054. uvs.push(u, v);
  34055. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34056. y = x * Math.sin(ang) + y * Math.cos(ang);
  34057. x = tmp;
  34058. // colors
  34059. if (faceColors) {
  34060. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34061. }
  34062. }
  34063. // indices from indexes
  34064. for (i = 0; i < fl - 2; i++) {
  34065. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34066. }
  34067. faceIdx += fl;
  34068. }
  34069. }
  34070. VertexData.ComputeNormals(positions, indices, normals);
  34071. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34072. var vertexData = new VertexData();
  34073. vertexData.positions = positions;
  34074. vertexData.indices = indices;
  34075. vertexData.normals = normals;
  34076. vertexData.uvs = uvs;
  34077. if (faceColors && flat) {
  34078. vertexData.colors = colors;
  34079. }
  34080. return vertexData;
  34081. };
  34082. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34083. /**
  34084. * Creates the VertexData of the Torus Knot.
  34085. */
  34086. VertexData.CreateTorusKnot = function (options) {
  34087. var indices = new Array();
  34088. var positions = new Array();
  34089. var normals = new Array();
  34090. var uvs = new Array();
  34091. var radius = options.radius || 2;
  34092. var tube = options.tube || 0.5;
  34093. var radialSegments = options.radialSegments || 32;
  34094. var tubularSegments = options.tubularSegments || 32;
  34095. var p = options.p || 2;
  34096. var q = options.q || 3;
  34097. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34098. // Helper
  34099. var getPos = function (angle) {
  34100. var cu = Math.cos(angle);
  34101. var su = Math.sin(angle);
  34102. var quOverP = q / p * angle;
  34103. var cs = Math.cos(quOverP);
  34104. var tx = radius * (2 + cs) * 0.5 * cu;
  34105. var ty = radius * (2 + cs) * su * 0.5;
  34106. var tz = radius * Math.sin(quOverP) * 0.5;
  34107. return new BABYLON.Vector3(tx, ty, tz);
  34108. };
  34109. // Vertices
  34110. var i;
  34111. var j;
  34112. for (i = 0; i <= radialSegments; i++) {
  34113. var modI = i % radialSegments;
  34114. var u = modI / radialSegments * 2 * p * Math.PI;
  34115. var p1 = getPos(u);
  34116. var p2 = getPos(u + 0.01);
  34117. var tang = p2.subtract(p1);
  34118. var n = p2.add(p1);
  34119. var bitan = BABYLON.Vector3.Cross(tang, n);
  34120. n = BABYLON.Vector3.Cross(bitan, tang);
  34121. bitan.normalize();
  34122. n.normalize();
  34123. for (j = 0; j < tubularSegments; j++) {
  34124. var modJ = j % tubularSegments;
  34125. var v = modJ / tubularSegments * 2 * Math.PI;
  34126. var cx = -tube * Math.cos(v);
  34127. var cy = tube * Math.sin(v);
  34128. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34129. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34130. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34131. uvs.push(i / radialSegments);
  34132. uvs.push(j / tubularSegments);
  34133. }
  34134. }
  34135. for (i = 0; i < radialSegments; i++) {
  34136. for (j = 0; j < tubularSegments; j++) {
  34137. var jNext = (j + 1) % tubularSegments;
  34138. var a = i * tubularSegments + j;
  34139. var b = (i + 1) * tubularSegments + j;
  34140. var c = (i + 1) * tubularSegments + jNext;
  34141. var d = i * tubularSegments + jNext;
  34142. indices.push(d);
  34143. indices.push(b);
  34144. indices.push(a);
  34145. indices.push(d);
  34146. indices.push(c);
  34147. indices.push(b);
  34148. }
  34149. }
  34150. // Normals
  34151. VertexData.ComputeNormals(positions, indices, normals);
  34152. // Sides
  34153. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34154. // Result
  34155. var vertexData = new VertexData();
  34156. vertexData.indices = indices;
  34157. vertexData.positions = positions;
  34158. vertexData.normals = normals;
  34159. vertexData.uvs = uvs;
  34160. return vertexData;
  34161. };
  34162. // Tools
  34163. /**
  34164. * @param {any} - positions (number[] or Float32Array)
  34165. * @param {any} - indices (number[] or Uint16Array)
  34166. * @param {any} - normals (number[] or Float32Array)
  34167. * options (optional) :
  34168. * facetPositions : optional array of facet positions (vector3)
  34169. * facetNormals : optional array of facet normals (vector3)
  34170. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34171. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34172. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34173. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34174. * bInfo : optional bounding info, required for facetPartitioning computation
  34175. * useRightHandedSystem: optional boolean to for right handed system computation
  34176. * depthSort : optional boolean to enable the facet depth sort computation
  34177. * distanceTo : optional Vector3 to compute the facet depth from this location
  34178. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34179. */
  34180. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34181. // temporary scalar variables
  34182. var index = 0; // facet index
  34183. var p1p2x = 0.0; // p1p2 vector x coordinate
  34184. var p1p2y = 0.0; // p1p2 vector y coordinate
  34185. var p1p2z = 0.0; // p1p2 vector z coordinate
  34186. var p3p2x = 0.0; // p3p2 vector x coordinate
  34187. var p3p2y = 0.0; // p3p2 vector y coordinate
  34188. var p3p2z = 0.0; // p3p2 vector z coordinate
  34189. var faceNormalx = 0.0; // facet normal x coordinate
  34190. var faceNormaly = 0.0; // facet normal y coordinate
  34191. var faceNormalz = 0.0; // facet normal z coordinate
  34192. var length = 0.0; // facet normal length before normalization
  34193. var v1x = 0; // vector1 x index in the positions array
  34194. var v1y = 0; // vector1 y index in the positions array
  34195. var v1z = 0; // vector1 z index in the positions array
  34196. var v2x = 0; // vector2 x index in the positions array
  34197. var v2y = 0; // vector2 y index in the positions array
  34198. var v2z = 0; // vector2 z index in the positions array
  34199. var v3x = 0; // vector3 x index in the positions array
  34200. var v3y = 0; // vector3 y index in the positions array
  34201. var v3z = 0; // vector3 z index in the positions array
  34202. var computeFacetNormals = false;
  34203. var computeFacetPositions = false;
  34204. var computeFacetPartitioning = false;
  34205. var computeDepthSort = false;
  34206. var faceNormalSign = 1;
  34207. var ratio = 0;
  34208. var distanceTo = null;
  34209. if (options) {
  34210. computeFacetNormals = (options.facetNormals) ? true : false;
  34211. computeFacetPositions = (options.facetPositions) ? true : false;
  34212. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34213. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34214. ratio = options.ratio || 0;
  34215. computeDepthSort = (options.depthSort) ? true : false;
  34216. distanceTo = (options.distanceTo);
  34217. if (computeDepthSort) {
  34218. if (distanceTo === undefined) {
  34219. distanceTo = BABYLON.Vector3.Zero();
  34220. }
  34221. var depthSortedFacets = options.depthSortedFacets;
  34222. }
  34223. }
  34224. // facetPartitioning reinit if needed
  34225. var xSubRatio = 0;
  34226. var ySubRatio = 0;
  34227. var zSubRatio = 0;
  34228. var subSq = 0;
  34229. if (computeFacetPartitioning && options && options.bbSize) {
  34230. var ox = 0; // X partitioning index for facet position
  34231. var oy = 0; // Y partinioning index for facet position
  34232. var oz = 0; // Z partinioning index for facet position
  34233. var b1x = 0; // X partitioning index for facet v1 vertex
  34234. var b1y = 0; // Y partitioning index for facet v1 vertex
  34235. var b1z = 0; // z partitioning index for facet v1 vertex
  34236. var b2x = 0; // X partitioning index for facet v2 vertex
  34237. var b2y = 0; // Y partitioning index for facet v2 vertex
  34238. var b2z = 0; // Z partitioning index for facet v2 vertex
  34239. var b3x = 0; // X partitioning index for facet v3 vertex
  34240. var b3y = 0; // Y partitioning index for facet v3 vertex
  34241. var b3z = 0; // Z partitioning index for facet v3 vertex
  34242. var block_idx_o = 0; // facet barycenter block index
  34243. var block_idx_v1 = 0; // v1 vertex block index
  34244. var block_idx_v2 = 0; // v2 vertex block index
  34245. var block_idx_v3 = 0; // v3 vertex block index
  34246. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34247. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34248. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34249. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34250. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34251. subSq = options.subDiv.max * options.subDiv.max;
  34252. options.facetPartitioning.length = 0;
  34253. }
  34254. // reset the normals
  34255. for (index = 0; index < positions.length; index++) {
  34256. normals[index] = 0.0;
  34257. }
  34258. // Loop : 1 indice triplet = 1 facet
  34259. var nbFaces = (indices.length / 3) | 0;
  34260. for (index = 0; index < nbFaces; index++) {
  34261. // get the indexes of the coordinates of each vertex of the facet
  34262. v1x = indices[index * 3] * 3;
  34263. v1y = v1x + 1;
  34264. v1z = v1x + 2;
  34265. v2x = indices[index * 3 + 1] * 3;
  34266. v2y = v2x + 1;
  34267. v2z = v2x + 2;
  34268. v3x = indices[index * 3 + 2] * 3;
  34269. v3y = v3x + 1;
  34270. v3z = v3x + 2;
  34271. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34272. p1p2y = positions[v1y] - positions[v2y];
  34273. p1p2z = positions[v1z] - positions[v2z];
  34274. p3p2x = positions[v3x] - positions[v2x];
  34275. p3p2y = positions[v3y] - positions[v2y];
  34276. p3p2z = positions[v3z] - positions[v2z];
  34277. // compute the face normal with the cross product
  34278. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34279. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34280. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34281. // normalize this normal and store it in the array facetData
  34282. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34283. length = (length === 0) ? 1.0 : length;
  34284. faceNormalx /= length;
  34285. faceNormaly /= length;
  34286. faceNormalz /= length;
  34287. if (computeFacetNormals && options) {
  34288. options.facetNormals[index].x = faceNormalx;
  34289. options.facetNormals[index].y = faceNormaly;
  34290. options.facetNormals[index].z = faceNormalz;
  34291. }
  34292. if (computeFacetPositions && options) {
  34293. // compute and the facet barycenter coordinates in the array facetPositions
  34294. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34295. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34296. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34297. }
  34298. if (computeFacetPartitioning && options) {
  34299. // store the facet indexes in arrays in the main facetPartitioning array :
  34300. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34301. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  34302. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  34303. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  34304. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34305. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34306. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34307. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34308. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34309. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34310. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34311. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34312. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34313. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34314. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34315. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34316. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34317. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34318. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34319. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34320. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34321. // push each facet index in each block containing the vertex
  34322. options.facetPartitioning[block_idx_v1].push(index);
  34323. if (block_idx_v2 != block_idx_v1) {
  34324. options.facetPartitioning[block_idx_v2].push(index);
  34325. }
  34326. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34327. options.facetPartitioning[block_idx_v3].push(index);
  34328. }
  34329. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34330. options.facetPartitioning[block_idx_o].push(index);
  34331. }
  34332. }
  34333. if (computeDepthSort && options && options.facetPositions) {
  34334. var dsf = depthSortedFacets[index];
  34335. dsf.ind = index * 3;
  34336. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  34337. }
  34338. // compute the normals anyway
  34339. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34340. normals[v1y] += faceNormaly;
  34341. normals[v1z] += faceNormalz;
  34342. normals[v2x] += faceNormalx;
  34343. normals[v2y] += faceNormaly;
  34344. normals[v2z] += faceNormalz;
  34345. normals[v3x] += faceNormalx;
  34346. normals[v3y] += faceNormaly;
  34347. normals[v3z] += faceNormalz;
  34348. }
  34349. // last normalization of each normal
  34350. for (index = 0; index < normals.length / 3; index++) {
  34351. faceNormalx = normals[index * 3];
  34352. faceNormaly = normals[index * 3 + 1];
  34353. faceNormalz = normals[index * 3 + 2];
  34354. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34355. length = (length === 0) ? 1.0 : length;
  34356. faceNormalx /= length;
  34357. faceNormaly /= length;
  34358. faceNormalz /= length;
  34359. normals[index * 3] = faceNormalx;
  34360. normals[index * 3 + 1] = faceNormaly;
  34361. normals[index * 3 + 2] = faceNormalz;
  34362. }
  34363. };
  34364. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  34365. var li = indices.length;
  34366. var ln = normals.length;
  34367. var i;
  34368. var n;
  34369. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34370. switch (sideOrientation) {
  34371. case BABYLON.Mesh.FRONTSIDE:
  34372. // nothing changed
  34373. break;
  34374. case BABYLON.Mesh.BACKSIDE:
  34375. var tmp;
  34376. // indices
  34377. for (i = 0; i < li; i += 3) {
  34378. tmp = indices[i];
  34379. indices[i] = indices[i + 2];
  34380. indices[i + 2] = tmp;
  34381. }
  34382. // normals
  34383. for (n = 0; n < ln; n++) {
  34384. normals[n] = -normals[n];
  34385. }
  34386. break;
  34387. case BABYLON.Mesh.DOUBLESIDE:
  34388. // positions
  34389. var lp = positions.length;
  34390. var l = lp / 3;
  34391. for (var p = 0; p < lp; p++) {
  34392. positions[lp + p] = positions[p];
  34393. }
  34394. // indices
  34395. for (i = 0; i < li; i += 3) {
  34396. indices[i + li] = indices[i + 2] + l;
  34397. indices[i + 1 + li] = indices[i + 1] + l;
  34398. indices[i + 2 + li] = indices[i] + l;
  34399. }
  34400. // normals
  34401. for (n = 0; n < ln; n++) {
  34402. normals[ln + n] = -normals[n];
  34403. }
  34404. // uvs
  34405. var lu = uvs.length;
  34406. var u = 0;
  34407. for (u = 0; u < lu; u++) {
  34408. uvs[u + lu] = uvs[u];
  34409. }
  34410. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34411. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34412. u = 0;
  34413. for (i = 0; i < lu / 2; i++) {
  34414. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  34415. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  34416. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  34417. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  34418. u += 2;
  34419. }
  34420. break;
  34421. }
  34422. };
  34423. /**
  34424. * Creates a new VertexData from the imported parameters.
  34425. */
  34426. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  34427. var vertexData = new VertexData();
  34428. // positions
  34429. var positions = parsedVertexData.positions;
  34430. if (positions) {
  34431. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  34432. }
  34433. // normals
  34434. var normals = parsedVertexData.normals;
  34435. if (normals) {
  34436. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  34437. }
  34438. // tangents
  34439. var tangents = parsedVertexData.tangents;
  34440. if (tangents) {
  34441. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  34442. }
  34443. // uvs
  34444. var uvs = parsedVertexData.uvs;
  34445. if (uvs) {
  34446. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  34447. }
  34448. // uv2s
  34449. var uv2s = parsedVertexData.uv2s;
  34450. if (uv2s) {
  34451. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  34452. }
  34453. // uv3s
  34454. var uv3s = parsedVertexData.uv3s;
  34455. if (uv3s) {
  34456. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  34457. }
  34458. // uv4s
  34459. var uv4s = parsedVertexData.uv4s;
  34460. if (uv4s) {
  34461. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  34462. }
  34463. // uv5s
  34464. var uv5s = parsedVertexData.uv5s;
  34465. if (uv5s) {
  34466. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  34467. }
  34468. // uv6s
  34469. var uv6s = parsedVertexData.uv6s;
  34470. if (uv6s) {
  34471. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  34472. }
  34473. // colors
  34474. var colors = parsedVertexData.colors;
  34475. if (colors) {
  34476. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  34477. }
  34478. // matricesIndices
  34479. var matricesIndices = parsedVertexData.matricesIndices;
  34480. if (matricesIndices) {
  34481. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  34482. }
  34483. // matricesWeights
  34484. var matricesWeights = parsedVertexData.matricesWeights;
  34485. if (matricesWeights) {
  34486. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  34487. }
  34488. // indices
  34489. var indices = parsedVertexData.indices;
  34490. if (indices) {
  34491. vertexData.indices = indices;
  34492. }
  34493. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  34494. };
  34495. return VertexData;
  34496. }());
  34497. BABYLON.VertexData = VertexData;
  34498. })(BABYLON || (BABYLON = {}));
  34499. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  34500. var BABYLON;
  34501. (function (BABYLON) {
  34502. /**
  34503. * Class used to store geometry data (vertex buffers + index buffer)
  34504. */
  34505. var Geometry = /** @class */ (function () {
  34506. /**
  34507. * Creates a new geometry
  34508. * @param id defines the unique ID
  34509. * @param scene defines the hosting scene
  34510. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  34511. * @param updatable defines if geometry must be updatable (false by default)
  34512. * @param mesh defines the mesh that will be associated with the geometry
  34513. */
  34514. function Geometry(id, scene, vertexData, updatable, mesh) {
  34515. if (updatable === void 0) { updatable = false; }
  34516. if (mesh === void 0) { mesh = null; }
  34517. /**
  34518. * Gets the delay loading state of the geometry (none by default which means not delayed)
  34519. */
  34520. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34521. this._totalVertices = 0;
  34522. this._isDisposed = false;
  34523. this._indexBufferIsUpdatable = false;
  34524. this.id = id;
  34525. this._engine = scene.getEngine();
  34526. this._meshes = [];
  34527. this._scene = scene;
  34528. //Init vertex buffer cache
  34529. this._vertexBuffers = {};
  34530. this._indices = [];
  34531. this._updatable = updatable;
  34532. // vertexData
  34533. if (vertexData) {
  34534. this.setAllVerticesData(vertexData, updatable);
  34535. }
  34536. else {
  34537. this._totalVertices = 0;
  34538. this._indices = [];
  34539. }
  34540. if (this._engine.getCaps().vertexArrayObject) {
  34541. this._vertexArrayObjects = {};
  34542. }
  34543. // applyToMesh
  34544. if (mesh) {
  34545. if (mesh.getClassName() === "LinesMesh") {
  34546. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34547. this.updateExtend();
  34548. }
  34549. this.applyToMesh(mesh);
  34550. mesh.computeWorldMatrix(true);
  34551. }
  34552. }
  34553. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34554. /**
  34555. * 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
  34556. */
  34557. get: function () {
  34558. return this._boundingBias;
  34559. },
  34560. /**
  34561. * 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
  34562. */
  34563. set: function (value) {
  34564. if (this._boundingBias && this._boundingBias.equals(value)) {
  34565. return;
  34566. }
  34567. this._boundingBias = value.clone();
  34568. this.updateBoundingInfo(true, null);
  34569. },
  34570. enumerable: true,
  34571. configurable: true
  34572. });
  34573. /**
  34574. * Static function used to attach a new empty geometry to a mesh
  34575. * @param mesh defines the mesh to attach the geometry to
  34576. * @returns the new {BABYLON.Geometry}
  34577. */
  34578. Geometry.CreateGeometryForMesh = function (mesh) {
  34579. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  34580. geometry.applyToMesh(mesh);
  34581. return geometry;
  34582. };
  34583. Object.defineProperty(Geometry.prototype, "extend", {
  34584. /**
  34585. * Gets the current extend of the geometry
  34586. */
  34587. get: function () {
  34588. return this._extend;
  34589. },
  34590. enumerable: true,
  34591. configurable: true
  34592. });
  34593. /**
  34594. * Gets the hosting scene
  34595. * @returns the hosting {BABYLON.Scene}
  34596. */
  34597. Geometry.prototype.getScene = function () {
  34598. return this._scene;
  34599. };
  34600. /**
  34601. * Gets the hosting engine
  34602. * @returns the hosting {BABYLON.Engine}
  34603. */
  34604. Geometry.prototype.getEngine = function () {
  34605. return this._engine;
  34606. };
  34607. /**
  34608. * Defines if the geometry is ready to use
  34609. * @returns true if the geometry is ready to be used
  34610. */
  34611. Geometry.prototype.isReady = function () {
  34612. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34613. };
  34614. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  34615. /**
  34616. * Gets a value indicating that the geometry should not be serialized
  34617. */
  34618. get: function () {
  34619. for (var index = 0; index < this._meshes.length; index++) {
  34620. if (!this._meshes[index].doNotSerialize) {
  34621. return false;
  34622. }
  34623. }
  34624. return true;
  34625. },
  34626. enumerable: true,
  34627. configurable: true
  34628. });
  34629. /** @ignore */
  34630. Geometry.prototype._rebuild = function () {
  34631. if (this._vertexArrayObjects) {
  34632. this._vertexArrayObjects = {};
  34633. }
  34634. // Index buffer
  34635. if (this._meshes.length !== 0 && this._indices) {
  34636. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34637. }
  34638. // Vertex buffers
  34639. for (var key in this._vertexBuffers) {
  34640. var vertexBuffer = this._vertexBuffers[key];
  34641. vertexBuffer._rebuild();
  34642. }
  34643. };
  34644. /**
  34645. * Affects all gemetry data in one call
  34646. * @param vertexData defines the geometry data
  34647. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  34648. */
  34649. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34650. vertexData.applyToGeometry(this, updatable);
  34651. this.notifyUpdate();
  34652. };
  34653. /**
  34654. * Set specific vertex data
  34655. * @param kind defines the data kind (Position, normal, etc...)
  34656. * @param data defines the vertex data to use
  34657. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  34658. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  34659. */
  34660. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34661. if (updatable === void 0) { updatable = false; }
  34662. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34663. this.setVerticesBuffer(buffer);
  34664. };
  34665. /**
  34666. * Removes a specific vertex data
  34667. * @param kind defines the data kind (Position, normal, etc...)
  34668. */
  34669. Geometry.prototype.removeVerticesData = function (kind) {
  34670. if (this._vertexBuffers[kind]) {
  34671. this._vertexBuffers[kind].dispose();
  34672. delete this._vertexBuffers[kind];
  34673. }
  34674. };
  34675. /**
  34676. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  34677. * @param buffer defines the vertex buffer to use
  34678. */
  34679. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34680. var kind = buffer.getKind();
  34681. if (this._vertexBuffers[kind]) {
  34682. this._vertexBuffers[kind].dispose();
  34683. }
  34684. this._vertexBuffers[kind] = buffer;
  34685. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34686. var data = buffer.getData();
  34687. var stride = buffer.getStrideSize();
  34688. this._totalVertices = data.length / stride;
  34689. this.updateExtend(data, stride);
  34690. this._resetPointsArrayCache();
  34691. var meshes = this._meshes;
  34692. var numOfMeshes = meshes.length;
  34693. for (var index = 0; index < numOfMeshes; index++) {
  34694. var mesh = meshes[index];
  34695. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34696. mesh._createGlobalSubMesh(false);
  34697. mesh.computeWorldMatrix(true);
  34698. }
  34699. }
  34700. this.notifyUpdate(kind);
  34701. if (this._vertexArrayObjects) {
  34702. this._disposeVertexArrayObjects();
  34703. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  34704. }
  34705. };
  34706. /**
  34707. * Update a specific vertex buffer
  34708. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  34709. * It will do nothing if the buffer is not updatable
  34710. * @param kind defines the data kind (Position, normal, etc...)
  34711. * @param data defines the data to use
  34712. * @param offset defines the offset in the target buffer where to store the data
  34713. */
  34714. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34715. var vertexBuffer = this.getVertexBuffer(kind);
  34716. if (!vertexBuffer) {
  34717. return;
  34718. }
  34719. vertexBuffer.updateDirectly(data, offset);
  34720. this.notifyUpdate(kind);
  34721. };
  34722. /**
  34723. * Update a specific vertex buffer
  34724. * This function will create a new buffer if the current one is not updatable
  34725. * @param kind defines the data kind (Position, normal, etc...)
  34726. * @param data defines the data to use
  34727. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  34728. */
  34729. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34730. if (updateExtends === void 0) { updateExtends = false; }
  34731. var vertexBuffer = this.getVertexBuffer(kind);
  34732. if (!vertexBuffer) {
  34733. return;
  34734. }
  34735. vertexBuffer.update(data);
  34736. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34737. var stride = vertexBuffer.getStrideSize();
  34738. this._totalVertices = data.length / stride;
  34739. this.updateBoundingInfo(updateExtends, data);
  34740. }
  34741. this.notifyUpdate(kind);
  34742. };
  34743. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34744. if (updateExtends) {
  34745. this.updateExtend(data);
  34746. }
  34747. var meshes = this._meshes;
  34748. var numOfMeshes = meshes.length;
  34749. this._resetPointsArrayCache();
  34750. for (var index = 0; index < numOfMeshes; index++) {
  34751. var mesh = meshes[index];
  34752. if (updateExtends) {
  34753. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34754. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34755. var subMesh = mesh.subMeshes[subIndex];
  34756. subMesh.refreshBoundingInfo();
  34757. }
  34758. }
  34759. }
  34760. };
  34761. /** @ignore */
  34762. Geometry.prototype._bind = function (effect, indexToBind) {
  34763. if (!effect) {
  34764. return;
  34765. }
  34766. if (indexToBind === undefined) {
  34767. indexToBind = this._indexBuffer;
  34768. }
  34769. var vbs = this.getVertexBuffers();
  34770. if (!vbs) {
  34771. return;
  34772. }
  34773. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  34774. this._engine.bindBuffers(vbs, indexToBind, effect);
  34775. return;
  34776. }
  34777. // Using VAO
  34778. if (!this._vertexArrayObjects[effect.key]) {
  34779. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  34780. }
  34781. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  34782. };
  34783. /**
  34784. * Gets total number of vertices
  34785. * @returns the total number of vertices
  34786. */
  34787. Geometry.prototype.getTotalVertices = function () {
  34788. if (!this.isReady()) {
  34789. return 0;
  34790. }
  34791. return this._totalVertices;
  34792. };
  34793. /**
  34794. * Gets a specific vertex data attached to this geometry
  34795. * @param kind defines the data kind (Position, normal, etc...)
  34796. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34797. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  34798. * @returns a float array containing vertex data
  34799. */
  34800. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  34801. var vertexBuffer = this.getVertexBuffer(kind);
  34802. if (!vertexBuffer) {
  34803. return null;
  34804. }
  34805. var orig = vertexBuffer.getData();
  34806. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  34807. return orig;
  34808. }
  34809. else {
  34810. var len = orig.length;
  34811. var copy = [];
  34812. for (var i = 0; i < len; i++) {
  34813. copy.push(orig[i]);
  34814. }
  34815. return copy;
  34816. }
  34817. };
  34818. /**
  34819. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  34820. * @param kind defines the data kind (Position, normal, etc...)
  34821. * @returns true if the vertex buffer with the specified kind is updatable
  34822. */
  34823. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  34824. var vb = this._vertexBuffers[kind];
  34825. if (!vb) {
  34826. return false;
  34827. }
  34828. return vb.isUpdatable();
  34829. };
  34830. /**
  34831. * Gets a specific vertex buffer
  34832. * @param kind defines the data kind (Position, normal, etc...)
  34833. * @returns a {BABYLON.VertexBuffer}
  34834. */
  34835. Geometry.prototype.getVertexBuffer = function (kind) {
  34836. if (!this.isReady()) {
  34837. return null;
  34838. }
  34839. return this._vertexBuffers[kind];
  34840. };
  34841. /**
  34842. * Returns all vertex buffers
  34843. * @return an object holding all vertex buffers indexed by kind
  34844. */
  34845. Geometry.prototype.getVertexBuffers = function () {
  34846. if (!this.isReady()) {
  34847. return null;
  34848. }
  34849. return this._vertexBuffers;
  34850. };
  34851. /**
  34852. * Gets a boolean indicating if specific vertex buffer is present
  34853. * @param kind defines the data kind (Position, normal, etc...)
  34854. * @returns true if data is present
  34855. */
  34856. Geometry.prototype.isVerticesDataPresent = function (kind) {
  34857. if (!this._vertexBuffers) {
  34858. if (this._delayInfo) {
  34859. return this._delayInfo.indexOf(kind) !== -1;
  34860. }
  34861. return false;
  34862. }
  34863. return this._vertexBuffers[kind] !== undefined;
  34864. };
  34865. /**
  34866. * Gets a list of all attached data kinds (Position, normal, etc...)
  34867. * @returns a list of string containing all kinds
  34868. */
  34869. Geometry.prototype.getVerticesDataKinds = function () {
  34870. var result = [];
  34871. var kind;
  34872. if (!this._vertexBuffers && this._delayInfo) {
  34873. for (kind in this._delayInfo) {
  34874. result.push(kind);
  34875. }
  34876. }
  34877. else {
  34878. for (kind in this._vertexBuffers) {
  34879. result.push(kind);
  34880. }
  34881. }
  34882. return result;
  34883. };
  34884. /**
  34885. * Update index buffer
  34886. * @param indices defines the indices to store in the index buffer
  34887. * @param offset defines the offset in the target buffer where to store the data
  34888. */
  34889. Geometry.prototype.updateIndices = function (indices, offset) {
  34890. if (!this._indexBuffer) {
  34891. return;
  34892. }
  34893. if (!this._indexBufferIsUpdatable) {
  34894. this.setIndices(indices, null, true);
  34895. }
  34896. else {
  34897. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  34898. }
  34899. };
  34900. /**
  34901. * Creates a new index buffer
  34902. * @param indices defines the indices to store in the index buffer
  34903. * @param totalVertices defines the total number of vertices (could be null)
  34904. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  34905. */
  34906. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  34907. if (totalVertices === void 0) { totalVertices = null; }
  34908. if (updatable === void 0) { updatable = false; }
  34909. if (this._indexBuffer) {
  34910. this._engine._releaseBuffer(this._indexBuffer);
  34911. }
  34912. this._disposeVertexArrayObjects();
  34913. this._indices = indices;
  34914. this._indexBufferIsUpdatable = updatable;
  34915. if (this._meshes.length !== 0 && this._indices) {
  34916. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  34917. }
  34918. if (totalVertices != undefined) {
  34919. this._totalVertices = totalVertices;
  34920. }
  34921. var meshes = this._meshes;
  34922. var numOfMeshes = meshes.length;
  34923. for (var index = 0; index < numOfMeshes; index++) {
  34924. meshes[index]._createGlobalSubMesh(true);
  34925. }
  34926. this.notifyUpdate();
  34927. };
  34928. /**
  34929. * Return the total number of indices
  34930. * @returns the total number of indices
  34931. */
  34932. Geometry.prototype.getTotalIndices = function () {
  34933. if (!this.isReady()) {
  34934. return 0;
  34935. }
  34936. return this._indices.length;
  34937. };
  34938. /**
  34939. * Gets the index buffer array
  34940. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34941. * @returns the index buffer array
  34942. */
  34943. Geometry.prototype.getIndices = function (copyWhenShared) {
  34944. if (!this.isReady()) {
  34945. return null;
  34946. }
  34947. var orig = this._indices;
  34948. if (!copyWhenShared || this._meshes.length === 1) {
  34949. return orig;
  34950. }
  34951. else {
  34952. var len = orig.length;
  34953. var copy = [];
  34954. for (var i = 0; i < len; i++) {
  34955. copy.push(orig[i]);
  34956. }
  34957. return copy;
  34958. }
  34959. };
  34960. /**
  34961. * Gets the index buffer
  34962. * @return the index buffer
  34963. */
  34964. Geometry.prototype.getIndexBuffer = function () {
  34965. if (!this.isReady()) {
  34966. return null;
  34967. }
  34968. return this._indexBuffer;
  34969. };
  34970. /** @ignore */
  34971. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  34972. if (effect === void 0) { effect = null; }
  34973. if (!effect || !this._vertexArrayObjects) {
  34974. return;
  34975. }
  34976. if (this._vertexArrayObjects[effect.key]) {
  34977. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  34978. delete this._vertexArrayObjects[effect.key];
  34979. }
  34980. };
  34981. /**
  34982. * Release the associated resources for a specific mesh
  34983. * @param mesh defines the source mesh
  34984. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  34985. */
  34986. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  34987. var meshes = this._meshes;
  34988. var index = meshes.indexOf(mesh);
  34989. if (index === -1) {
  34990. return;
  34991. }
  34992. meshes.splice(index, 1);
  34993. mesh._geometry = null;
  34994. if (meshes.length === 0 && shouldDispose) {
  34995. this.dispose();
  34996. }
  34997. };
  34998. /**
  34999. * Apply current geometry to a given mesh
  35000. * @param mesh defines the mesh to apply geometry to
  35001. */
  35002. Geometry.prototype.applyToMesh = function (mesh) {
  35003. if (mesh._geometry === this) {
  35004. return;
  35005. }
  35006. var previousGeometry = mesh._geometry;
  35007. if (previousGeometry) {
  35008. previousGeometry.releaseForMesh(mesh);
  35009. }
  35010. var meshes = this._meshes;
  35011. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35012. mesh._geometry = this;
  35013. this._scene.pushGeometry(this);
  35014. meshes.push(mesh);
  35015. if (this.isReady()) {
  35016. this._applyToMesh(mesh);
  35017. }
  35018. else {
  35019. mesh._boundingInfo = this._boundingInfo;
  35020. }
  35021. };
  35022. Geometry.prototype.updateExtend = function (data, stride) {
  35023. if (data === void 0) { data = null; }
  35024. if (!data) {
  35025. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35026. }
  35027. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35028. };
  35029. Geometry.prototype._applyToMesh = function (mesh) {
  35030. var numOfMeshes = this._meshes.length;
  35031. // vertexBuffers
  35032. for (var kind in this._vertexBuffers) {
  35033. if (numOfMeshes === 1) {
  35034. this._vertexBuffers[kind].create();
  35035. }
  35036. var buffer = this._vertexBuffers[kind].getBuffer();
  35037. if (buffer)
  35038. buffer.references = numOfMeshes;
  35039. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35040. if (!this._extend) {
  35041. this.updateExtend(this._vertexBuffers[kind].getData());
  35042. }
  35043. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35044. mesh._createGlobalSubMesh(false);
  35045. //bounding info was just created again, world matrix should be applied again.
  35046. mesh._updateBoundingInfo();
  35047. }
  35048. }
  35049. // indexBuffer
  35050. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35051. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35052. }
  35053. if (this._indexBuffer) {
  35054. this._indexBuffer.references = numOfMeshes;
  35055. }
  35056. };
  35057. Geometry.prototype.notifyUpdate = function (kind) {
  35058. if (this.onGeometryUpdated) {
  35059. this.onGeometryUpdated(this, kind);
  35060. }
  35061. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35062. var mesh = _a[_i];
  35063. mesh._markSubMeshesAsAttributesDirty();
  35064. }
  35065. };
  35066. /**
  35067. * Load the geometry if it was flagged as delay loaded
  35068. * @param scene defines the hosting scene
  35069. * @param onLoaded defines a callback called when the geometry is loaded
  35070. */
  35071. Geometry.prototype.load = function (scene, onLoaded) {
  35072. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35073. return;
  35074. }
  35075. if (this.isReady()) {
  35076. if (onLoaded) {
  35077. onLoaded();
  35078. }
  35079. return;
  35080. }
  35081. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35082. this._queueLoad(scene, onLoaded);
  35083. };
  35084. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35085. var _this = this;
  35086. if (!this.delayLoadingFile) {
  35087. return;
  35088. }
  35089. scene._addPendingData(this);
  35090. scene._loadFile(this.delayLoadingFile, function (data) {
  35091. if (!_this._delayLoadingFunction) {
  35092. return;
  35093. }
  35094. _this._delayLoadingFunction(JSON.parse(data), _this);
  35095. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35096. _this._delayInfo = [];
  35097. scene._removePendingData(_this);
  35098. var meshes = _this._meshes;
  35099. var numOfMeshes = meshes.length;
  35100. for (var index = 0; index < numOfMeshes; index++) {
  35101. _this._applyToMesh(meshes[index]);
  35102. }
  35103. if (onLoaded) {
  35104. onLoaded();
  35105. }
  35106. }, undefined, true);
  35107. };
  35108. /**
  35109. * Invert the geometry to move from a right handed system to a left handed one.
  35110. */
  35111. Geometry.prototype.toLeftHanded = function () {
  35112. // Flip faces
  35113. var tIndices = this.getIndices(false);
  35114. if (tIndices != null && tIndices.length > 0) {
  35115. for (var i = 0; i < tIndices.length; i += 3) {
  35116. var tTemp = tIndices[i + 0];
  35117. tIndices[i + 0] = tIndices[i + 2];
  35118. tIndices[i + 2] = tTemp;
  35119. }
  35120. this.setIndices(tIndices);
  35121. }
  35122. // Negate position.z
  35123. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35124. if (tPositions != null && tPositions.length > 0) {
  35125. for (var i = 0; i < tPositions.length; i += 3) {
  35126. tPositions[i + 2] = -tPositions[i + 2];
  35127. }
  35128. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35129. }
  35130. // Negate normal.z
  35131. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35132. if (tNormals != null && tNormals.length > 0) {
  35133. for (var i = 0; i < tNormals.length; i += 3) {
  35134. tNormals[i + 2] = -tNormals[i + 2];
  35135. }
  35136. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35137. }
  35138. };
  35139. // Cache
  35140. /** @ignore */
  35141. Geometry.prototype._resetPointsArrayCache = function () {
  35142. this._positions = null;
  35143. };
  35144. /** @ignore */
  35145. Geometry.prototype._generatePointsArray = function () {
  35146. if (this._positions)
  35147. return true;
  35148. this._positions = [];
  35149. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35150. if (!data) {
  35151. return false;
  35152. }
  35153. for (var index = 0; index < data.length; index += 3) {
  35154. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35155. }
  35156. return true;
  35157. };
  35158. /**
  35159. * Gets a value indicating if the geometry is disposed
  35160. * @returns true if the geometry was disposed
  35161. */
  35162. Geometry.prototype.isDisposed = function () {
  35163. return this._isDisposed;
  35164. };
  35165. Geometry.prototype._disposeVertexArrayObjects = function () {
  35166. if (this._vertexArrayObjects) {
  35167. for (var kind in this._vertexArrayObjects) {
  35168. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35169. }
  35170. this._vertexArrayObjects = {};
  35171. }
  35172. };
  35173. /**
  35174. * Free all associated resources
  35175. */
  35176. Geometry.prototype.dispose = function () {
  35177. var meshes = this._meshes;
  35178. var numOfMeshes = meshes.length;
  35179. var index;
  35180. for (index = 0; index < numOfMeshes; index++) {
  35181. this.releaseForMesh(meshes[index]);
  35182. }
  35183. this._meshes = [];
  35184. this._disposeVertexArrayObjects();
  35185. for (var kind in this._vertexBuffers) {
  35186. this._vertexBuffers[kind].dispose();
  35187. }
  35188. this._vertexBuffers = {};
  35189. this._totalVertices = 0;
  35190. if (this._indexBuffer) {
  35191. this._engine._releaseBuffer(this._indexBuffer);
  35192. }
  35193. this._indexBuffer = null;
  35194. this._indices = [];
  35195. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35196. this.delayLoadingFile = null;
  35197. this._delayLoadingFunction = null;
  35198. this._delayInfo = [];
  35199. this._boundingInfo = null;
  35200. this._scene.removeGeometry(this);
  35201. this._isDisposed = true;
  35202. };
  35203. /**
  35204. * Clone the current geometry into a new geometry
  35205. * @param id defines the unique ID of the new geometry
  35206. * @returns a new geometry object
  35207. */
  35208. Geometry.prototype.copy = function (id) {
  35209. var vertexData = new BABYLON.VertexData();
  35210. vertexData.indices = [];
  35211. var indices = this.getIndices();
  35212. if (indices) {
  35213. for (var index = 0; index < indices.length; index++) {
  35214. vertexData.indices.push(indices[index]);
  35215. }
  35216. }
  35217. var updatable = false;
  35218. var stopChecking = false;
  35219. var kind;
  35220. for (kind in this._vertexBuffers) {
  35221. // using slice() to make a copy of the array and not just reference it
  35222. var data = this.getVerticesData(kind);
  35223. if (data instanceof Float32Array) {
  35224. vertexData.set(new Float32Array(data), kind);
  35225. }
  35226. else {
  35227. vertexData.set(data.slice(0), kind);
  35228. }
  35229. if (!stopChecking) {
  35230. var vb = this.getVertexBuffer(kind);
  35231. if (vb) {
  35232. updatable = vb.isUpdatable();
  35233. stopChecking = !updatable;
  35234. }
  35235. }
  35236. }
  35237. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35238. geometry.delayLoadState = this.delayLoadState;
  35239. geometry.delayLoadingFile = this.delayLoadingFile;
  35240. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35241. for (kind in this._delayInfo) {
  35242. geometry._delayInfo = geometry._delayInfo || [];
  35243. geometry._delayInfo.push(kind);
  35244. }
  35245. // Bounding info
  35246. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35247. return geometry;
  35248. };
  35249. /**
  35250. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35251. * @return a JSON representation of the current geometry data (without the vertices data)
  35252. */
  35253. Geometry.prototype.serialize = function () {
  35254. var serializationObject = {};
  35255. serializationObject.id = this.id;
  35256. serializationObject.updatable = this._updatable;
  35257. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35258. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35259. }
  35260. return serializationObject;
  35261. };
  35262. Geometry.prototype.toNumberArray = function (origin) {
  35263. if (Array.isArray(origin)) {
  35264. return origin;
  35265. }
  35266. else {
  35267. return Array.prototype.slice.call(origin);
  35268. }
  35269. };
  35270. /**
  35271. * Serialize all vertices data into a JSON oject
  35272. * @returns a JSON representation of the current geometry data
  35273. */
  35274. Geometry.prototype.serializeVerticeData = function () {
  35275. var serializationObject = this.serialize();
  35276. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35277. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35278. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35279. serializationObject.positions._updatable = true;
  35280. }
  35281. }
  35282. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35283. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35284. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35285. serializationObject.normals._updatable = true;
  35286. }
  35287. }
  35288. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35289. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35290. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35291. serializationObject.tangets._updatable = true;
  35292. }
  35293. }
  35294. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35295. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  35296. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  35297. serializationObject.uvs._updatable = true;
  35298. }
  35299. }
  35300. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35301. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  35302. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  35303. serializationObject.uv2s._updatable = true;
  35304. }
  35305. }
  35306. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35307. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  35308. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  35309. serializationObject.uv3s._updatable = true;
  35310. }
  35311. }
  35312. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35313. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  35314. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  35315. serializationObject.uv4s._updatable = true;
  35316. }
  35317. }
  35318. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35319. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  35320. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  35321. serializationObject.uv5s._updatable = true;
  35322. }
  35323. }
  35324. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35325. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  35326. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  35327. serializationObject.uv6s._updatable = true;
  35328. }
  35329. }
  35330. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35331. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  35332. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  35333. serializationObject.colors._updatable = true;
  35334. }
  35335. }
  35336. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35337. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  35338. serializationObject.matricesIndices._isExpanded = true;
  35339. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35340. serializationObject.matricesIndices._updatable = true;
  35341. }
  35342. }
  35343. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35344. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  35345. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35346. serializationObject.matricesWeights._updatable = true;
  35347. }
  35348. }
  35349. serializationObject.indices = this.toNumberArray(this.getIndices());
  35350. return serializationObject;
  35351. };
  35352. // Statics
  35353. /**
  35354. * Extracts a clone of a mesh geometry
  35355. * @param mesh defines the source mesh
  35356. * @param id defines the unique ID of the new geometry object
  35357. * @returns the new geometry object
  35358. */
  35359. Geometry.ExtractFromMesh = function (mesh, id) {
  35360. var geometry = mesh._geometry;
  35361. if (!geometry) {
  35362. return null;
  35363. }
  35364. return geometry.copy(id);
  35365. };
  35366. /**
  35367. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35368. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35369. * Be aware Math.random() could cause collisions, but:
  35370. * "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"
  35371. * @returns a string containing a new GUID
  35372. */
  35373. Geometry.RandomId = function () {
  35374. return BABYLON.Tools.RandomId();
  35375. };
  35376. /** @ignore */
  35377. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  35378. var scene = mesh.getScene();
  35379. // Geometry
  35380. var geometryId = parsedGeometry.geometryId;
  35381. if (geometryId) {
  35382. var geometry = scene.getGeometryByID(geometryId);
  35383. if (geometry) {
  35384. geometry.applyToMesh(mesh);
  35385. }
  35386. }
  35387. else if (parsedGeometry instanceof ArrayBuffer) {
  35388. var binaryInfo = mesh._binaryInfo;
  35389. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  35390. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  35391. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  35392. }
  35393. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  35394. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  35395. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  35396. }
  35397. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  35398. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  35399. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  35400. }
  35401. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  35402. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  35403. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  35404. }
  35405. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  35406. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  35407. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  35408. }
  35409. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  35410. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  35411. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  35412. }
  35413. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  35414. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  35415. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  35416. }
  35417. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  35418. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  35419. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  35420. }
  35421. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  35422. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  35423. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  35424. }
  35425. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  35426. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  35427. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  35428. }
  35429. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  35430. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  35431. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  35432. }
  35433. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  35434. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  35435. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  35436. }
  35437. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  35438. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  35439. mesh.setIndices(indicesData, null);
  35440. }
  35441. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  35442. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  35443. mesh.subMeshes = [];
  35444. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  35445. var materialIndex = subMeshesData[(i * 5) + 0];
  35446. var verticesStart = subMeshesData[(i * 5) + 1];
  35447. var verticesCount = subMeshesData[(i * 5) + 2];
  35448. var indexStart = subMeshesData[(i * 5) + 3];
  35449. var indexCount = subMeshesData[(i * 5) + 4];
  35450. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  35451. }
  35452. }
  35453. }
  35454. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  35455. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  35456. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  35457. if (parsedGeometry.tangents) {
  35458. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  35459. }
  35460. if (parsedGeometry.uvs) {
  35461. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  35462. }
  35463. if (parsedGeometry.uvs2) {
  35464. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  35465. }
  35466. if (parsedGeometry.uvs3) {
  35467. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  35468. }
  35469. if (parsedGeometry.uvs4) {
  35470. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  35471. }
  35472. if (parsedGeometry.uvs5) {
  35473. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  35474. }
  35475. if (parsedGeometry.uvs6) {
  35476. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  35477. }
  35478. if (parsedGeometry.colors) {
  35479. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  35480. }
  35481. if (parsedGeometry.matricesIndices) {
  35482. if (!parsedGeometry.matricesIndices._isExpanded) {
  35483. var floatIndices = [];
  35484. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  35485. var matricesIndex = parsedGeometry.matricesIndices[i];
  35486. floatIndices.push(matricesIndex & 0x000000FF);
  35487. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35488. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35489. floatIndices.push(matricesIndex >> 24);
  35490. }
  35491. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  35492. }
  35493. else {
  35494. delete parsedGeometry.matricesIndices._isExpanded;
  35495. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  35496. }
  35497. }
  35498. if (parsedGeometry.matricesIndicesExtra) {
  35499. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  35500. var floatIndices = [];
  35501. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  35502. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  35503. floatIndices.push(matricesIndex & 0x000000FF);
  35504. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35505. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35506. floatIndices.push(matricesIndex >> 24);
  35507. }
  35508. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  35509. }
  35510. else {
  35511. delete parsedGeometry.matricesIndices._isExpanded;
  35512. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  35513. }
  35514. }
  35515. if (parsedGeometry.matricesWeights) {
  35516. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  35517. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  35518. }
  35519. if (parsedGeometry.matricesWeightsExtra) {
  35520. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  35521. }
  35522. mesh.setIndices(parsedGeometry.indices, null);
  35523. }
  35524. // SubMeshes
  35525. if (parsedGeometry.subMeshes) {
  35526. mesh.subMeshes = [];
  35527. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35528. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35529. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35530. }
  35531. }
  35532. // Flat shading
  35533. if (mesh._shouldGenerateFlatShading) {
  35534. mesh.convertToFlatShadedMesh();
  35535. delete mesh._shouldGenerateFlatShading;
  35536. }
  35537. // Update
  35538. mesh.computeWorldMatrix(true);
  35539. // Octree
  35540. var sceneOctree = scene.selectionOctree;
  35541. if (sceneOctree !== undefined && sceneOctree !== null) {
  35542. sceneOctree.addMesh(mesh);
  35543. }
  35544. };
  35545. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  35546. var epsilon = 1e-3;
  35547. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  35548. return;
  35549. }
  35550. var noInfluenceBoneIndex = 0.0;
  35551. if (parsedGeometry.skeletonId > -1) {
  35552. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  35553. if (!skeleton) {
  35554. return;
  35555. }
  35556. noInfluenceBoneIndex = skeleton.bones.length;
  35557. }
  35558. else {
  35559. return;
  35560. }
  35561. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35562. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35563. var matricesWeights = parsedGeometry.matricesWeights;
  35564. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  35565. var influencers = parsedGeometry.numBoneInfluencer;
  35566. var size = matricesWeights.length;
  35567. for (var i = 0; i < size; i += 4) {
  35568. var weight = 0.0;
  35569. var firstZeroWeight = -1;
  35570. for (var j = 0; j < 4; j++) {
  35571. var w = matricesWeights[i + j];
  35572. weight += w;
  35573. if (w < epsilon && firstZeroWeight < 0) {
  35574. firstZeroWeight = j;
  35575. }
  35576. }
  35577. if (matricesWeightsExtra) {
  35578. for (var j = 0; j < 4; j++) {
  35579. var w = matricesWeightsExtra[i + j];
  35580. weight += w;
  35581. if (w < epsilon && firstZeroWeight < 0) {
  35582. firstZeroWeight = j + 4;
  35583. }
  35584. }
  35585. }
  35586. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  35587. firstZeroWeight = influencers - 1;
  35588. }
  35589. if (weight > epsilon) {
  35590. var mweight = 1.0 / weight;
  35591. for (var j = 0; j < 4; j++) {
  35592. matricesWeights[i + j] *= mweight;
  35593. }
  35594. if (matricesWeightsExtra) {
  35595. for (var j = 0; j < 4; j++) {
  35596. matricesWeightsExtra[i + j] *= mweight;
  35597. }
  35598. }
  35599. }
  35600. else {
  35601. if (firstZeroWeight >= 4) {
  35602. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  35603. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  35604. }
  35605. else {
  35606. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  35607. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  35608. }
  35609. }
  35610. }
  35611. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  35612. if (parsedGeometry.matricesWeightsExtra) {
  35613. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  35614. }
  35615. };
  35616. /**
  35617. * Create a new geometry from persisted data (Using .babylon file format)
  35618. * @param parsedVertexData defines the persisted data
  35619. * @param scene defines the hosting scene
  35620. * @param rootUrl defines the root url to use to load assets (like delayed data)
  35621. * @returns the new geometry object
  35622. */
  35623. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35624. if (scene.getGeometryByID(parsedVertexData.id)) {
  35625. return null; // null since geometry could be something else than a box...
  35626. }
  35627. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  35628. if (BABYLON.Tags) {
  35629. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35630. }
  35631. if (parsedVertexData.delayLoadingFile) {
  35632. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35633. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35634. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35635. geometry._delayInfo = [];
  35636. if (parsedVertexData.hasUVs) {
  35637. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35638. }
  35639. if (parsedVertexData.hasUVs2) {
  35640. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35641. }
  35642. if (parsedVertexData.hasUVs3) {
  35643. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35644. }
  35645. if (parsedVertexData.hasUVs4) {
  35646. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35647. }
  35648. if (parsedVertexData.hasUVs5) {
  35649. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35650. }
  35651. if (parsedVertexData.hasUVs6) {
  35652. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35653. }
  35654. if (parsedVertexData.hasColors) {
  35655. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35656. }
  35657. if (parsedVertexData.hasMatricesIndices) {
  35658. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35659. }
  35660. if (parsedVertexData.hasMatricesWeights) {
  35661. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35662. }
  35663. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35664. }
  35665. else {
  35666. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35667. }
  35668. scene.pushGeometry(geometry, true);
  35669. return geometry;
  35670. };
  35671. return Geometry;
  35672. }());
  35673. BABYLON.Geometry = Geometry;
  35674. // Primitives
  35675. /// Abstract class
  35676. /**
  35677. * Abstract class used to provide common services for all typed geometries
  35678. */
  35679. var _PrimitiveGeometry = /** @class */ (function (_super) {
  35680. __extends(_PrimitiveGeometry, _super);
  35681. /**
  35682. * Creates a new typed geometry
  35683. * @param id defines the unique ID of the geometry
  35684. * @param scene defines the hosting scene
  35685. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35686. * @param mesh defines the hosting mesh (can be null)
  35687. */
  35688. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  35689. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  35690. if (mesh === void 0) { mesh = null; }
  35691. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  35692. _this._canBeRegenerated = _canBeRegenerated;
  35693. _this._beingRegenerated = true;
  35694. _this.regenerate();
  35695. _this._beingRegenerated = false;
  35696. return _this;
  35697. }
  35698. /**
  35699. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  35700. * @returns true if the geometry can be regenerated
  35701. */
  35702. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  35703. return this._canBeRegenerated;
  35704. };
  35705. /**
  35706. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  35707. */
  35708. _PrimitiveGeometry.prototype.regenerate = function () {
  35709. if (!this._canBeRegenerated) {
  35710. return;
  35711. }
  35712. this._beingRegenerated = true;
  35713. this.setAllVerticesData(this._regenerateVertexData(), false);
  35714. this._beingRegenerated = false;
  35715. };
  35716. /**
  35717. * Clone the geometry
  35718. * @param id defines the unique ID of the new geometry
  35719. * @returns the new geometry
  35720. */
  35721. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  35722. return _super.prototype.copy.call(this, id);
  35723. };
  35724. // overrides
  35725. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35726. if (!this._beingRegenerated) {
  35727. return;
  35728. }
  35729. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35730. };
  35731. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  35732. if (!this._beingRegenerated) {
  35733. return;
  35734. }
  35735. _super.prototype.setVerticesData.call(this, kind, data, false);
  35736. };
  35737. // to override
  35738. /** @ignore */
  35739. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  35740. throw new Error("Abstract method");
  35741. };
  35742. _PrimitiveGeometry.prototype.copy = function (id) {
  35743. throw new Error("Must be overriden in sub-classes.");
  35744. };
  35745. _PrimitiveGeometry.prototype.serialize = function () {
  35746. var serializationObject = _super.prototype.serialize.call(this);
  35747. serializationObject.canBeRegenerated = this.canBeRegenerated();
  35748. return serializationObject;
  35749. };
  35750. return _PrimitiveGeometry;
  35751. }(Geometry));
  35752. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  35753. /**
  35754. * Creates a ribbon geometry
  35755. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  35756. */
  35757. var RibbonGeometry = /** @class */ (function (_super) {
  35758. __extends(RibbonGeometry, _super);
  35759. /**
  35760. * Creates a ribbon geometry
  35761. * @param id defines the unique ID of the geometry
  35762. * @param scene defines the hosting scene
  35763. * @param pathArray defines the array of paths to use
  35764. * @param closeArray defines if the last path and the first path must be joined
  35765. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  35766. * @param offset defines the offset between points
  35767. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35768. * @param mesh defines the hosting mesh (can be null)
  35769. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35770. */
  35771. function RibbonGeometry(id, scene,
  35772. /**
  35773. * Defines the array of paths to use
  35774. */
  35775. pathArray,
  35776. /**
  35777. * Defines if the last and first points of each path in your pathArray must be joined
  35778. */
  35779. closeArray,
  35780. /**
  35781. * Defines if the last and first points of each path in your pathArray must be joined
  35782. */
  35783. closePath,
  35784. /**
  35785. * Defines the offset between points
  35786. */
  35787. offset, canBeRegenerated, mesh,
  35788. /**
  35789. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35790. */
  35791. side) {
  35792. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35793. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35794. _this.pathArray = pathArray;
  35795. _this.closeArray = closeArray;
  35796. _this.closePath = closePath;
  35797. _this.offset = offset;
  35798. _this.side = side;
  35799. return _this;
  35800. }
  35801. /** @ignore */
  35802. RibbonGeometry.prototype._regenerateVertexData = function () {
  35803. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  35804. };
  35805. RibbonGeometry.prototype.copy = function (id) {
  35806. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  35807. };
  35808. return RibbonGeometry;
  35809. }(_PrimitiveGeometry));
  35810. BABYLON.RibbonGeometry = RibbonGeometry;
  35811. /**
  35812. * Creates a box geometry
  35813. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  35814. */
  35815. var BoxGeometry = /** @class */ (function (_super) {
  35816. __extends(BoxGeometry, _super);
  35817. /**
  35818. * Creates a box geometry
  35819. * @param id defines the unique ID of the geometry
  35820. * @param scene defines the hosting scene
  35821. * @param size defines the zise of the box (width, height and depth are the same)
  35822. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35823. * @param mesh defines the hosting mesh (can be null)
  35824. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35825. */
  35826. function BoxGeometry(id, scene,
  35827. /**
  35828. * Defines the zise of the box (width, height and depth are the same)
  35829. */
  35830. size, canBeRegenerated, mesh,
  35831. /**
  35832. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35833. */
  35834. side) {
  35835. if (mesh === void 0) { mesh = null; }
  35836. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35837. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35838. _this.size = size;
  35839. _this.side = side;
  35840. return _this;
  35841. }
  35842. BoxGeometry.prototype._regenerateVertexData = function () {
  35843. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  35844. };
  35845. BoxGeometry.prototype.copy = function (id) {
  35846. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  35847. };
  35848. BoxGeometry.prototype.serialize = function () {
  35849. var serializationObject = _super.prototype.serialize.call(this);
  35850. serializationObject.size = this.size;
  35851. return serializationObject;
  35852. };
  35853. BoxGeometry.Parse = function (parsedBox, scene) {
  35854. if (scene.getGeometryByID(parsedBox.id)) {
  35855. return null; // null since geometry could be something else than a box...
  35856. }
  35857. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  35858. if (BABYLON.Tags) {
  35859. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  35860. }
  35861. scene.pushGeometry(box, true);
  35862. return box;
  35863. };
  35864. return BoxGeometry;
  35865. }(_PrimitiveGeometry));
  35866. BABYLON.BoxGeometry = BoxGeometry;
  35867. /**
  35868. * Creates a sphere geometry
  35869. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  35870. */
  35871. var SphereGeometry = /** @class */ (function (_super) {
  35872. __extends(SphereGeometry, _super);
  35873. /**
  35874. * Create a new sphere geometry
  35875. * @param id defines the unique ID of the geometry
  35876. * @param scene defines the hosting scene
  35877. * @param segments defines the number of segments to use to create the sphere
  35878. * @param diameter defines the diameter of the sphere
  35879. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35880. * @param mesh defines the hosting mesh (can be null)
  35881. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35882. */
  35883. function SphereGeometry(id, scene,
  35884. /**
  35885. * Defines the number of segments to use to create the sphere
  35886. */
  35887. segments,
  35888. /**
  35889. * Defines the diameter of the sphere
  35890. */
  35891. diameter, canBeRegenerated, mesh,
  35892. /**
  35893. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35894. */
  35895. side) {
  35896. if (mesh === void 0) { mesh = null; }
  35897. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35898. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35899. _this.segments = segments;
  35900. _this.diameter = diameter;
  35901. _this.side = side;
  35902. return _this;
  35903. }
  35904. SphereGeometry.prototype._regenerateVertexData = function () {
  35905. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  35906. };
  35907. SphereGeometry.prototype.copy = function (id) {
  35908. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  35909. };
  35910. SphereGeometry.prototype.serialize = function () {
  35911. var serializationObject = _super.prototype.serialize.call(this);
  35912. serializationObject.segments = this.segments;
  35913. serializationObject.diameter = this.diameter;
  35914. return serializationObject;
  35915. };
  35916. SphereGeometry.Parse = function (parsedSphere, scene) {
  35917. if (scene.getGeometryByID(parsedSphere.id)) {
  35918. return null; // null since geometry could be something else than a sphere...
  35919. }
  35920. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  35921. if (BABYLON.Tags) {
  35922. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  35923. }
  35924. scene.pushGeometry(sphere, true);
  35925. return sphere;
  35926. };
  35927. return SphereGeometry;
  35928. }(_PrimitiveGeometry));
  35929. BABYLON.SphereGeometry = SphereGeometry;
  35930. /**
  35931. * Creates a disc geometry
  35932. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  35933. */
  35934. var DiscGeometry = /** @class */ (function (_super) {
  35935. __extends(DiscGeometry, _super);
  35936. /**
  35937. * Creates a new disc geometry
  35938. * @param id defines the unique ID of the geometry
  35939. * @param scene defines the hosting scene
  35940. * @param radius defines the radius of the disc
  35941. * @param tessellation defines the tesselation factor to apply to the disc
  35942. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35943. * @param mesh defines the hosting mesh (can be null)
  35944. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35945. */
  35946. function DiscGeometry(id, scene,
  35947. /**
  35948. * Defines the radius of the disc
  35949. */
  35950. radius,
  35951. /**
  35952. * Defines the tesselation factor to apply to the disc
  35953. */
  35954. tessellation, canBeRegenerated, mesh,
  35955. /**
  35956. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35957. */
  35958. side) {
  35959. if (mesh === void 0) { mesh = null; }
  35960. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35961. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35962. _this.radius = radius;
  35963. _this.tessellation = tessellation;
  35964. _this.side = side;
  35965. return _this;
  35966. }
  35967. DiscGeometry.prototype._regenerateVertexData = function () {
  35968. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  35969. };
  35970. DiscGeometry.prototype.copy = function (id) {
  35971. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  35972. };
  35973. return DiscGeometry;
  35974. }(_PrimitiveGeometry));
  35975. BABYLON.DiscGeometry = DiscGeometry;
  35976. /**
  35977. * Creates a new cylinder geometry
  35978. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  35979. */
  35980. var CylinderGeometry = /** @class */ (function (_super) {
  35981. __extends(CylinderGeometry, _super);
  35982. /**
  35983. * Creates a new cylinder geometry
  35984. * @param id defines the unique ID of the geometry
  35985. * @param scene defines the hosting scene
  35986. * @param height defines the height of the cylinder
  35987. * @param diameterTop defines the diameter of the cylinder's top cap
  35988. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  35989. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  35990. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  35991. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35992. * @param mesh defines the hosting mesh (can be null)
  35993. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35994. */
  35995. function CylinderGeometry(id, scene,
  35996. /**
  35997. * Defines the height of the cylinder
  35998. */
  35999. height,
  36000. /**
  36001. * Defines the diameter of the cylinder's top cap
  36002. */
  36003. diameterTop,
  36004. /**
  36005. * Defines the diameter of the cylinder's bottom cap
  36006. */
  36007. diameterBottom,
  36008. /**
  36009. * Defines the tessellation factor to apply to the cylinder
  36010. */
  36011. tessellation,
  36012. /**
  36013. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36014. */
  36015. subdivisions, canBeRegenerated, mesh,
  36016. /**
  36017. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36018. */
  36019. side) {
  36020. if (subdivisions === void 0) { subdivisions = 1; }
  36021. if (mesh === void 0) { mesh = null; }
  36022. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36023. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36024. _this.height = height;
  36025. _this.diameterTop = diameterTop;
  36026. _this.diameterBottom = diameterBottom;
  36027. _this.tessellation = tessellation;
  36028. _this.subdivisions = subdivisions;
  36029. _this.side = side;
  36030. return _this;
  36031. }
  36032. CylinderGeometry.prototype._regenerateVertexData = function () {
  36033. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36034. };
  36035. CylinderGeometry.prototype.copy = function (id) {
  36036. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36037. };
  36038. CylinderGeometry.prototype.serialize = function () {
  36039. var serializationObject = _super.prototype.serialize.call(this);
  36040. serializationObject.height = this.height;
  36041. serializationObject.diameterTop = this.diameterTop;
  36042. serializationObject.diameterBottom = this.diameterBottom;
  36043. serializationObject.tessellation = this.tessellation;
  36044. return serializationObject;
  36045. };
  36046. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36047. if (scene.getGeometryByID(parsedCylinder.id)) {
  36048. return null; // null since geometry could be something else than a cylinder...
  36049. }
  36050. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36051. if (BABYLON.Tags) {
  36052. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36053. }
  36054. scene.pushGeometry(cylinder, true);
  36055. return cylinder;
  36056. };
  36057. return CylinderGeometry;
  36058. }(_PrimitiveGeometry));
  36059. BABYLON.CylinderGeometry = CylinderGeometry;
  36060. /**
  36061. * Creates a new torus geometry
  36062. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36063. */
  36064. var TorusGeometry = /** @class */ (function (_super) {
  36065. __extends(TorusGeometry, _super);
  36066. /**
  36067. * Creates a new torus geometry
  36068. * @param id defines the unique ID of the geometry
  36069. * @param scene defines the hosting scene
  36070. * @param diameter defines the diameter of the torus
  36071. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36072. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36073. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36074. * @param mesh defines the hosting mesh (can be null)
  36075. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36076. */
  36077. function TorusGeometry(id, scene,
  36078. /**
  36079. * Defines the diameter of the torus
  36080. */
  36081. diameter,
  36082. /**
  36083. * Defines the thickness of the torus (ie. internal diameter)
  36084. */
  36085. thickness,
  36086. /**
  36087. * Defines the tesselation factor to apply to the torus
  36088. */
  36089. tessellation, canBeRegenerated, mesh,
  36090. /**
  36091. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36092. */
  36093. side) {
  36094. if (mesh === void 0) { mesh = null; }
  36095. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36096. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36097. _this.diameter = diameter;
  36098. _this.thickness = thickness;
  36099. _this.tessellation = tessellation;
  36100. _this.side = side;
  36101. return _this;
  36102. }
  36103. TorusGeometry.prototype._regenerateVertexData = function () {
  36104. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36105. };
  36106. TorusGeometry.prototype.copy = function (id) {
  36107. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36108. };
  36109. TorusGeometry.prototype.serialize = function () {
  36110. var serializationObject = _super.prototype.serialize.call(this);
  36111. serializationObject.diameter = this.diameter;
  36112. serializationObject.thickness = this.thickness;
  36113. serializationObject.tessellation = this.tessellation;
  36114. return serializationObject;
  36115. };
  36116. TorusGeometry.Parse = function (parsedTorus, scene) {
  36117. if (scene.getGeometryByID(parsedTorus.id)) {
  36118. return null; // null since geometry could be something else than a torus...
  36119. }
  36120. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36121. if (BABYLON.Tags) {
  36122. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36123. }
  36124. scene.pushGeometry(torus, true);
  36125. return torus;
  36126. };
  36127. return TorusGeometry;
  36128. }(_PrimitiveGeometry));
  36129. BABYLON.TorusGeometry = TorusGeometry;
  36130. /**
  36131. * Creates a new ground geometry
  36132. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36133. */
  36134. var GroundGeometry = /** @class */ (function (_super) {
  36135. __extends(GroundGeometry, _super);
  36136. /**
  36137. * Creates a new ground geometry
  36138. * @param id defines the unique ID of the geometry
  36139. * @param scene defines the hosting scene
  36140. * @param width defines the width of the ground
  36141. * @param height defines the height of the ground
  36142. * @param subdivisions defines the subdivisions to apply to the ground
  36143. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36144. * @param mesh defines the hosting mesh (can be null)
  36145. */
  36146. function GroundGeometry(id, scene,
  36147. /**
  36148. * Defines the width of the ground
  36149. */
  36150. width,
  36151. /**
  36152. * Defines the height of the ground
  36153. */
  36154. height,
  36155. /**
  36156. * Defines the subdivisions to apply to the ground
  36157. */
  36158. subdivisions, canBeRegenerated, mesh) {
  36159. if (mesh === void 0) { mesh = null; }
  36160. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36161. _this.width = width;
  36162. _this.height = height;
  36163. _this.subdivisions = subdivisions;
  36164. return _this;
  36165. }
  36166. GroundGeometry.prototype._regenerateVertexData = function () {
  36167. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36168. };
  36169. GroundGeometry.prototype.copy = function (id) {
  36170. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36171. };
  36172. GroundGeometry.prototype.serialize = function () {
  36173. var serializationObject = _super.prototype.serialize.call(this);
  36174. serializationObject.width = this.width;
  36175. serializationObject.height = this.height;
  36176. serializationObject.subdivisions = this.subdivisions;
  36177. return serializationObject;
  36178. };
  36179. GroundGeometry.Parse = function (parsedGround, scene) {
  36180. if (scene.getGeometryByID(parsedGround.id)) {
  36181. return null; // null since geometry could be something else than a ground...
  36182. }
  36183. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36184. if (BABYLON.Tags) {
  36185. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36186. }
  36187. scene.pushGeometry(ground, true);
  36188. return ground;
  36189. };
  36190. return GroundGeometry;
  36191. }(_PrimitiveGeometry));
  36192. BABYLON.GroundGeometry = GroundGeometry;
  36193. /**
  36194. * Creates a tiled ground geometry
  36195. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36196. */
  36197. var TiledGroundGeometry = /** @class */ (function (_super) {
  36198. __extends(TiledGroundGeometry, _super);
  36199. /**
  36200. * Creates a tiled ground geometry
  36201. * @param id defines the unique ID of the geometry
  36202. * @param scene defines the hosting scene
  36203. * @param xmin defines the minimum value on X axis
  36204. * @param zmin defines the minimum value on Z axis
  36205. * @param xmax defines the maximum value on X axis
  36206. * @param zmax defines the maximum value on Z axis
  36207. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36208. * @param precision defines the precision to use when computing the tiles
  36209. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36210. * @param mesh defines the hosting mesh (can be null)
  36211. */
  36212. function TiledGroundGeometry(id, scene,
  36213. /**
  36214. * Defines the minimum value on X axis
  36215. */
  36216. xmin,
  36217. /**
  36218. * Defines the minimum value on Z axis
  36219. */
  36220. zmin,
  36221. /**
  36222. * Defines the maximum value on X axis
  36223. */
  36224. xmax,
  36225. /**
  36226. * Defines the maximum value on Z axis
  36227. */
  36228. zmax,
  36229. /**
  36230. * Defines the subdivisions to apply to the ground
  36231. */
  36232. subdivisions,
  36233. /**
  36234. * Defines the precision to use when computing the tiles
  36235. */
  36236. precision, canBeRegenerated, mesh) {
  36237. if (mesh === void 0) { mesh = null; }
  36238. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36239. _this.xmin = xmin;
  36240. _this.zmin = zmin;
  36241. _this.xmax = xmax;
  36242. _this.zmax = zmax;
  36243. _this.subdivisions = subdivisions;
  36244. _this.precision = precision;
  36245. return _this;
  36246. }
  36247. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36248. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36249. };
  36250. TiledGroundGeometry.prototype.copy = function (id) {
  36251. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36252. };
  36253. return TiledGroundGeometry;
  36254. }(_PrimitiveGeometry));
  36255. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36256. /**
  36257. * Creates a plane geometry
  36258. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36259. */
  36260. var PlaneGeometry = /** @class */ (function (_super) {
  36261. __extends(PlaneGeometry, _super);
  36262. /**
  36263. * Creates a plane geometry
  36264. * @param id defines the unique ID of the geometry
  36265. * @param scene defines the hosting scene
  36266. * @param size defines the size of the plane (width === height)
  36267. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36268. * @param mesh defines the hosting mesh (can be null)
  36269. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36270. */
  36271. function PlaneGeometry(id, scene,
  36272. /**
  36273. * Defines the size of the plane (width === height)
  36274. */
  36275. size, canBeRegenerated, mesh,
  36276. /**
  36277. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36278. */
  36279. side) {
  36280. if (mesh === void 0) { mesh = null; }
  36281. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36282. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36283. _this.size = size;
  36284. _this.side = side;
  36285. return _this;
  36286. }
  36287. PlaneGeometry.prototype._regenerateVertexData = function () {
  36288. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36289. };
  36290. PlaneGeometry.prototype.copy = function (id) {
  36291. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36292. };
  36293. PlaneGeometry.prototype.serialize = function () {
  36294. var serializationObject = _super.prototype.serialize.call(this);
  36295. serializationObject.size = this.size;
  36296. return serializationObject;
  36297. };
  36298. PlaneGeometry.Parse = function (parsedPlane, scene) {
  36299. if (scene.getGeometryByID(parsedPlane.id)) {
  36300. return null; // null since geometry could be something else than a ground...
  36301. }
  36302. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36303. if (BABYLON.Tags) {
  36304. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36305. }
  36306. scene.pushGeometry(plane, true);
  36307. return plane;
  36308. };
  36309. return PlaneGeometry;
  36310. }(_PrimitiveGeometry));
  36311. BABYLON.PlaneGeometry = PlaneGeometry;
  36312. /**
  36313. * Creates a torus knot geometry
  36314. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  36315. */
  36316. var TorusKnotGeometry = /** @class */ (function (_super) {
  36317. __extends(TorusKnotGeometry, _super);
  36318. /**
  36319. * Creates a torus knot geometry
  36320. * @param id defines the unique ID of the geometry
  36321. * @param scene defines the hosting scene
  36322. * @param radius defines the radius of the torus knot
  36323. * @param tube defines the thickness of the torus knot tube
  36324. * @param radialSegments defines the number of radial segments
  36325. * @param tubularSegments defines the number of tubular segments
  36326. * @param p defines the first number of windings
  36327. * @param q defines the second number of windings
  36328. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36329. * @param mesh defines the hosting mesh (can be null)
  36330. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36331. */
  36332. function TorusKnotGeometry(id, scene,
  36333. /**
  36334. * Defines the radius of the torus knot
  36335. */
  36336. radius,
  36337. /**
  36338. * Defines the thickness of the torus knot tube
  36339. */
  36340. tube,
  36341. /**
  36342. * Defines the number of radial segments
  36343. */
  36344. radialSegments,
  36345. /**
  36346. * Defines the number of tubular segments
  36347. */
  36348. tubularSegments,
  36349. /**
  36350. * Defines the first number of windings
  36351. */
  36352. p,
  36353. /**
  36354. * Defines the second number of windings
  36355. */
  36356. q, canBeRegenerated, mesh,
  36357. /**
  36358. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36359. */
  36360. side) {
  36361. if (mesh === void 0) { mesh = null; }
  36362. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36363. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36364. _this.radius = radius;
  36365. _this.tube = tube;
  36366. _this.radialSegments = radialSegments;
  36367. _this.tubularSegments = tubularSegments;
  36368. _this.p = p;
  36369. _this.q = q;
  36370. _this.side = side;
  36371. return _this;
  36372. }
  36373. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  36374. 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 });
  36375. };
  36376. TorusKnotGeometry.prototype.copy = function (id) {
  36377. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  36378. };
  36379. TorusKnotGeometry.prototype.serialize = function () {
  36380. var serializationObject = _super.prototype.serialize.call(this);
  36381. serializationObject.radius = this.radius;
  36382. serializationObject.tube = this.tube;
  36383. serializationObject.radialSegments = this.radialSegments;
  36384. serializationObject.tubularSegments = this.tubularSegments;
  36385. serializationObject.p = this.p;
  36386. serializationObject.q = this.q;
  36387. return serializationObject;
  36388. };
  36389. ;
  36390. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  36391. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  36392. return null; // null since geometry could be something else than a ground...
  36393. }
  36394. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  36395. if (BABYLON.Tags) {
  36396. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  36397. }
  36398. scene.pushGeometry(torusKnot, true);
  36399. return torusKnot;
  36400. };
  36401. return TorusKnotGeometry;
  36402. }(_PrimitiveGeometry));
  36403. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  36404. //}
  36405. })(BABYLON || (BABYLON = {}));
  36406. //# sourceMappingURL=babylon.geometry.js.map
  36407. var BABYLON;
  36408. (function (BABYLON) {
  36409. /**
  36410. * PostProcessManager is used to manage one or more post processes or post process pipelines
  36411. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  36412. */
  36413. var PostProcessManager = /** @class */ (function () {
  36414. /**
  36415. * Creates a new instance of @see PostProcess
  36416. * @param scene The scene that the post process is associated with.
  36417. */
  36418. function PostProcessManager(scene) {
  36419. this._vertexBuffers = {};
  36420. this._scene = scene;
  36421. }
  36422. PostProcessManager.prototype._prepareBuffers = function () {
  36423. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  36424. return;
  36425. }
  36426. // VBO
  36427. var vertices = [];
  36428. vertices.push(1, 1);
  36429. vertices.push(-1, 1);
  36430. vertices.push(-1, -1);
  36431. vertices.push(1, -1);
  36432. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  36433. this._buildIndexBuffer();
  36434. };
  36435. PostProcessManager.prototype._buildIndexBuffer = function () {
  36436. // Indices
  36437. var indices = [];
  36438. indices.push(0);
  36439. indices.push(1);
  36440. indices.push(2);
  36441. indices.push(0);
  36442. indices.push(2);
  36443. indices.push(3);
  36444. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  36445. };
  36446. /**
  36447. * Rebuilds the vertex buffers of the manager.
  36448. */
  36449. PostProcessManager.prototype._rebuild = function () {
  36450. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36451. if (!vb) {
  36452. return;
  36453. }
  36454. vb._rebuild();
  36455. this._buildIndexBuffer();
  36456. };
  36457. // Methods
  36458. /**
  36459. * Prepares a frame to be run through a post process.
  36460. * @param sourceTexture The input texture to the post procesess. (default: null)
  36461. * @param postProcesses An array of post processes to be run. (default: null)
  36462. * @returns True if the post processes were able to be run.
  36463. */
  36464. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  36465. if (sourceTexture === void 0) { sourceTexture = null; }
  36466. if (postProcesses === void 0) { postProcesses = null; }
  36467. var camera = this._scene.activeCamera;
  36468. if (!camera) {
  36469. return false;
  36470. }
  36471. var postProcesses = postProcesses || camera._postProcesses;
  36472. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36473. return false;
  36474. }
  36475. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  36476. return true;
  36477. };
  36478. /**
  36479. * Manually render a set of post processes to a texture.
  36480. * @param postProcesses An array of post processes to be run.
  36481. * @param targetTexture The target texture to render to.
  36482. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  36483. */
  36484. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  36485. if (targetTexture === void 0) { targetTexture = null; }
  36486. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36487. var engine = this._scene.getEngine();
  36488. for (var index = 0; index < postProcesses.length; index++) {
  36489. if (index < postProcesses.length - 1) {
  36490. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  36491. }
  36492. else {
  36493. if (targetTexture) {
  36494. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  36495. }
  36496. else {
  36497. engine.restoreDefaultFramebuffer();
  36498. }
  36499. }
  36500. var pp = postProcesses[index];
  36501. var effect = pp.apply();
  36502. if (effect) {
  36503. pp.onBeforeRenderObservable.notifyObservers(effect);
  36504. // VBOs
  36505. this._prepareBuffers();
  36506. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36507. // Draw order
  36508. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36509. pp.onAfterRenderObservable.notifyObservers(effect);
  36510. }
  36511. }
  36512. // Restore depth buffer
  36513. engine.setDepthBuffer(true);
  36514. engine.setDepthWrite(true);
  36515. };
  36516. /**
  36517. * Finalize the result of the output of the postprocesses.
  36518. * @param doNotPresent If true the result will not be displayed to the screen.
  36519. * @param targetTexture The target texture to render to.
  36520. * @param faceIndex The index of the face to bind the target texture to.
  36521. * @param postProcesses The array of post processes to render.
  36522. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  36523. */
  36524. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  36525. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36526. var camera = this._scene.activeCamera;
  36527. if (!camera) {
  36528. return;
  36529. }
  36530. postProcesses = postProcesses || camera._postProcesses;
  36531. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36532. return;
  36533. }
  36534. var engine = this._scene.getEngine();
  36535. for (var index = 0, len = postProcesses.length; index < len; index++) {
  36536. if (index < len - 1) {
  36537. postProcesses[index + 1].activate(camera, targetTexture);
  36538. }
  36539. else {
  36540. if (targetTexture) {
  36541. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  36542. }
  36543. else {
  36544. engine.restoreDefaultFramebuffer();
  36545. }
  36546. }
  36547. if (doNotPresent) {
  36548. break;
  36549. }
  36550. var pp = postProcesses[index];
  36551. var effect = pp.apply();
  36552. if (effect) {
  36553. pp.onBeforeRenderObservable.notifyObservers(effect);
  36554. // VBOs
  36555. this._prepareBuffers();
  36556. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36557. // Draw order
  36558. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36559. pp.onAfterRenderObservable.notifyObservers(effect);
  36560. }
  36561. }
  36562. // Restore states
  36563. engine.setDepthBuffer(true);
  36564. engine.setDepthWrite(true);
  36565. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36566. };
  36567. /**
  36568. * Disposes of the post process manager.
  36569. */
  36570. PostProcessManager.prototype.dispose = function () {
  36571. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36572. if (buffer) {
  36573. buffer.dispose();
  36574. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  36575. }
  36576. if (this._indexBuffer) {
  36577. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36578. this._indexBuffer = null;
  36579. }
  36580. };
  36581. return PostProcessManager;
  36582. }());
  36583. BABYLON.PostProcessManager = PostProcessManager;
  36584. })(BABYLON || (BABYLON = {}));
  36585. //# sourceMappingURL=babylon.postProcessManager.js.map
  36586. var BABYLON;
  36587. (function (BABYLON) {
  36588. /**
  36589. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  36590. */
  36591. var PerformanceMonitor = /** @class */ (function () {
  36592. /**
  36593. * constructor
  36594. * @param frameSampleSize The number of samples required to saturate the sliding window
  36595. */
  36596. function PerformanceMonitor(frameSampleSize) {
  36597. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  36598. this._enabled = true;
  36599. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  36600. }
  36601. /**
  36602. * Samples current frame
  36603. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  36604. */
  36605. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  36606. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  36607. if (!this._enabled)
  36608. return;
  36609. if (this._lastFrameTimeMs != null) {
  36610. var dt = timeMs - this._lastFrameTimeMs;
  36611. this._rollingFrameTime.add(dt);
  36612. }
  36613. this._lastFrameTimeMs = timeMs;
  36614. };
  36615. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  36616. /**
  36617. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36618. * @return Average frame time in milliseconds
  36619. */
  36620. get: function () {
  36621. return this._rollingFrameTime.average;
  36622. },
  36623. enumerable: true,
  36624. configurable: true
  36625. });
  36626. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  36627. /**
  36628. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36629. * @return Frame time variance in milliseconds squared
  36630. */
  36631. get: function () {
  36632. return this._rollingFrameTime.variance;
  36633. },
  36634. enumerable: true,
  36635. configurable: true
  36636. });
  36637. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  36638. /**
  36639. * Returns the frame time of the most recent frame
  36640. * @return Frame time in milliseconds
  36641. */
  36642. get: function () {
  36643. return this._rollingFrameTime.history(0);
  36644. },
  36645. enumerable: true,
  36646. configurable: true
  36647. });
  36648. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  36649. /**
  36650. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  36651. * @return Framerate in frames per second
  36652. */
  36653. get: function () {
  36654. return 1000.0 / this._rollingFrameTime.average;
  36655. },
  36656. enumerable: true,
  36657. configurable: true
  36658. });
  36659. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  36660. /**
  36661. * Returns the average framerate in frames per second using the most recent frame time
  36662. * @return Framerate in frames per second
  36663. */
  36664. get: function () {
  36665. var history = this._rollingFrameTime.history(0);
  36666. if (history === 0) {
  36667. return 0;
  36668. }
  36669. return 1000.0 / history;
  36670. },
  36671. enumerable: true,
  36672. configurable: true
  36673. });
  36674. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  36675. /**
  36676. * Returns true if enough samples have been taken to completely fill the sliding window
  36677. * @return true if saturated
  36678. */
  36679. get: function () {
  36680. return this._rollingFrameTime.isSaturated();
  36681. },
  36682. enumerable: true,
  36683. configurable: true
  36684. });
  36685. /**
  36686. * Enables contributions to the sliding window sample set
  36687. */
  36688. PerformanceMonitor.prototype.enable = function () {
  36689. this._enabled = true;
  36690. };
  36691. /**
  36692. * Disables contributions to the sliding window sample set
  36693. * Samples will not be interpolated over the disabled period
  36694. */
  36695. PerformanceMonitor.prototype.disable = function () {
  36696. this._enabled = false;
  36697. //clear last sample to avoid interpolating over the disabled period when next enabled
  36698. this._lastFrameTimeMs = null;
  36699. };
  36700. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  36701. /**
  36702. * Returns true if sampling is enabled
  36703. * @return true if enabled
  36704. */
  36705. get: function () {
  36706. return this._enabled;
  36707. },
  36708. enumerable: true,
  36709. configurable: true
  36710. });
  36711. /**
  36712. * Resets performance monitor
  36713. */
  36714. PerformanceMonitor.prototype.reset = function () {
  36715. //clear last sample to avoid interpolating over the disabled period when next enabled
  36716. this._lastFrameTimeMs = null;
  36717. //wipe record
  36718. this._rollingFrameTime.reset();
  36719. };
  36720. return PerformanceMonitor;
  36721. }());
  36722. BABYLON.PerformanceMonitor = PerformanceMonitor;
  36723. /**
  36724. * RollingAverage
  36725. *
  36726. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  36727. */
  36728. var RollingAverage = /** @class */ (function () {
  36729. /**
  36730. * constructor
  36731. * @param length The number of samples required to saturate the sliding window
  36732. */
  36733. function RollingAverage(length) {
  36734. this._samples = new Array(length);
  36735. this.reset();
  36736. }
  36737. /**
  36738. * Adds a sample to the sample set
  36739. * @param v The sample value
  36740. */
  36741. RollingAverage.prototype.add = function (v) {
  36742. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  36743. var delta;
  36744. //we need to check if we've already wrapped round
  36745. if (this.isSaturated()) {
  36746. //remove bottom of stack from mean
  36747. var bottomValue = this._samples[this._pos];
  36748. delta = bottomValue - this.average;
  36749. this.average -= delta / (this._sampleCount - 1);
  36750. this._m2 -= delta * (bottomValue - this.average);
  36751. }
  36752. else {
  36753. this._sampleCount++;
  36754. }
  36755. //add new value to mean
  36756. delta = v - this.average;
  36757. this.average += delta / (this._sampleCount);
  36758. this._m2 += delta * (v - this.average);
  36759. //set the new variance
  36760. this.variance = this._m2 / (this._sampleCount - 1);
  36761. this._samples[this._pos] = v;
  36762. this._pos++;
  36763. this._pos %= this._samples.length; //positive wrap around
  36764. };
  36765. /**
  36766. * Returns previously added values or null if outside of history or outside the sliding window domain
  36767. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  36768. * @return Value previously recorded with add() or null if outside of range
  36769. */
  36770. RollingAverage.prototype.history = function (i) {
  36771. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  36772. return 0;
  36773. }
  36774. var i0 = this._wrapPosition(this._pos - 1.0);
  36775. return this._samples[this._wrapPosition(i0 - i)];
  36776. };
  36777. /**
  36778. * Returns true if enough samples have been taken to completely fill the sliding window
  36779. * @return true if sample-set saturated
  36780. */
  36781. RollingAverage.prototype.isSaturated = function () {
  36782. return this._sampleCount >= this._samples.length;
  36783. };
  36784. /**
  36785. * Resets the rolling average (equivalent to 0 samples taken so far)
  36786. */
  36787. RollingAverage.prototype.reset = function () {
  36788. this.average = 0;
  36789. this.variance = 0;
  36790. this._sampleCount = 0;
  36791. this._pos = 0;
  36792. this._m2 = 0;
  36793. };
  36794. /**
  36795. * Wraps a value around the sample range boundaries
  36796. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  36797. * @return Wrapped position in sample range
  36798. */
  36799. RollingAverage.prototype._wrapPosition = function (i) {
  36800. var max = this._samples.length;
  36801. return ((i % max) + max) % max;
  36802. };
  36803. return RollingAverage;
  36804. }());
  36805. BABYLON.RollingAverage = RollingAverage;
  36806. })(BABYLON || (BABYLON = {}));
  36807. //# sourceMappingURL=babylon.performanceMonitor.js.map
  36808. var BABYLON;
  36809. (function (BABYLON) {
  36810. /**
  36811. * This groups together the common properties used for image processing either in direct forward pass
  36812. * or through post processing effect depending on the use of the image processing pipeline in your scene
  36813. * or not.
  36814. */
  36815. var ImageProcessingConfiguration = /** @class */ (function () {
  36816. function ImageProcessingConfiguration() {
  36817. /**
  36818. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  36819. */
  36820. this.colorCurves = new BABYLON.ColorCurves();
  36821. this._colorCurvesEnabled = false;
  36822. this._colorGradingEnabled = false;
  36823. this._colorGradingWithGreenDepth = true;
  36824. this._colorGradingBGR = true;
  36825. this._exposure = 1.0;
  36826. this._toneMappingEnabled = false;
  36827. this._contrast = 1.0;
  36828. /**
  36829. * Vignette stretch size.
  36830. */
  36831. this.vignetteStretch = 0;
  36832. /**
  36833. * Vignette centre X Offset.
  36834. */
  36835. this.vignetteCentreX = 0;
  36836. /**
  36837. * Vignette centre Y Offset.
  36838. */
  36839. this.vignetteCentreY = 0;
  36840. /**
  36841. * Vignette weight or intensity of the vignette effect.
  36842. */
  36843. this.vignetteWeight = 1.5;
  36844. /**
  36845. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  36846. * if vignetteEnabled is set to true.
  36847. */
  36848. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  36849. /**
  36850. * Camera field of view used by the Vignette effect.
  36851. */
  36852. this.vignetteCameraFov = 0.5;
  36853. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  36854. this._vignetteEnabled = false;
  36855. this._applyByPostProcess = false;
  36856. this._isEnabled = true;
  36857. /**
  36858. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  36859. * @type {BABYLON.Observable}
  36860. */
  36861. this.onUpdateParameters = new BABYLON.Observable();
  36862. }
  36863. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  36864. /**
  36865. * Gets wether the color curves effect is enabled.
  36866. */
  36867. get: function () {
  36868. return this._colorCurvesEnabled;
  36869. },
  36870. /**
  36871. * Sets wether the color curves effect is enabled.
  36872. */
  36873. set: function (value) {
  36874. if (this._colorCurvesEnabled === value) {
  36875. return;
  36876. }
  36877. this._colorCurvesEnabled = value;
  36878. this._updateParameters();
  36879. },
  36880. enumerable: true,
  36881. configurable: true
  36882. });
  36883. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  36884. /**
  36885. * Gets wether the color grading effect is enabled.
  36886. */
  36887. get: function () {
  36888. return this._colorGradingEnabled;
  36889. },
  36890. /**
  36891. * Sets wether the color grading effect is enabled.
  36892. */
  36893. set: function (value) {
  36894. if (this._colorGradingEnabled === value) {
  36895. return;
  36896. }
  36897. this._colorGradingEnabled = value;
  36898. this._updateParameters();
  36899. },
  36900. enumerable: true,
  36901. configurable: true
  36902. });
  36903. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  36904. /**
  36905. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  36906. */
  36907. get: function () {
  36908. return this._colorGradingWithGreenDepth;
  36909. },
  36910. /**
  36911. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  36912. */
  36913. set: function (value) {
  36914. if (this._colorGradingWithGreenDepth === value) {
  36915. return;
  36916. }
  36917. this._colorGradingWithGreenDepth = value;
  36918. this._updateParameters();
  36919. },
  36920. enumerable: true,
  36921. configurable: true
  36922. });
  36923. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  36924. /**
  36925. * Gets wether the color grading texture contains BGR values.
  36926. */
  36927. get: function () {
  36928. return this._colorGradingBGR;
  36929. },
  36930. /**
  36931. * Sets wether the color grading texture contains BGR values.
  36932. */
  36933. set: function (value) {
  36934. if (this._colorGradingBGR === value) {
  36935. return;
  36936. }
  36937. this._colorGradingBGR = value;
  36938. this._updateParameters();
  36939. },
  36940. enumerable: true,
  36941. configurable: true
  36942. });
  36943. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  36944. /**
  36945. * Gets the Exposure used in the effect.
  36946. */
  36947. get: function () {
  36948. return this._exposure;
  36949. },
  36950. /**
  36951. * Sets the Exposure used in the effect.
  36952. */
  36953. set: function (value) {
  36954. if (this._exposure === value) {
  36955. return;
  36956. }
  36957. this._exposure = value;
  36958. this._updateParameters();
  36959. },
  36960. enumerable: true,
  36961. configurable: true
  36962. });
  36963. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  36964. /**
  36965. * Gets wether the tone mapping effect is enabled.
  36966. */
  36967. get: function () {
  36968. return this._toneMappingEnabled;
  36969. },
  36970. /**
  36971. * Sets wether the tone mapping effect is enabled.
  36972. */
  36973. set: function (value) {
  36974. if (this._toneMappingEnabled === value) {
  36975. return;
  36976. }
  36977. this._toneMappingEnabled = value;
  36978. this._updateParameters();
  36979. },
  36980. enumerable: true,
  36981. configurable: true
  36982. });
  36983. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  36984. /**
  36985. * Gets the contrast used in the effect.
  36986. */
  36987. get: function () {
  36988. return this._contrast;
  36989. },
  36990. /**
  36991. * Sets the contrast used in the effect.
  36992. */
  36993. set: function (value) {
  36994. if (this._contrast === value) {
  36995. return;
  36996. }
  36997. this._contrast = value;
  36998. this._updateParameters();
  36999. },
  37000. enumerable: true,
  37001. configurable: true
  37002. });
  37003. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37004. /**
  37005. * Gets the vignette blend mode allowing different kind of effect.
  37006. */
  37007. get: function () {
  37008. return this._vignetteBlendMode;
  37009. },
  37010. /**
  37011. * Sets the vignette blend mode allowing different kind of effect.
  37012. */
  37013. set: function (value) {
  37014. if (this._vignetteBlendMode === value) {
  37015. return;
  37016. }
  37017. this._vignetteBlendMode = value;
  37018. this._updateParameters();
  37019. },
  37020. enumerable: true,
  37021. configurable: true
  37022. });
  37023. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37024. /**
  37025. * Gets wether the vignette effect is enabled.
  37026. */
  37027. get: function () {
  37028. return this._vignetteEnabled;
  37029. },
  37030. /**
  37031. * Sets wether the vignette effect is enabled.
  37032. */
  37033. set: function (value) {
  37034. if (this._vignetteEnabled === value) {
  37035. return;
  37036. }
  37037. this._vignetteEnabled = value;
  37038. this._updateParameters();
  37039. },
  37040. enumerable: true,
  37041. configurable: true
  37042. });
  37043. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37044. /**
  37045. * Gets wether the image processing is applied through a post process or not.
  37046. */
  37047. get: function () {
  37048. return this._applyByPostProcess;
  37049. },
  37050. /**
  37051. * Sets wether the image processing is applied through a post process or not.
  37052. */
  37053. set: function (value) {
  37054. if (this._applyByPostProcess === value) {
  37055. return;
  37056. }
  37057. this._applyByPostProcess = value;
  37058. this._updateParameters();
  37059. },
  37060. enumerable: true,
  37061. configurable: true
  37062. });
  37063. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37064. /**
  37065. * Gets wether the image processing is enabled or not.
  37066. */
  37067. get: function () {
  37068. return this._isEnabled;
  37069. },
  37070. /**
  37071. * Sets wether the image processing is enabled or not.
  37072. */
  37073. set: function (value) {
  37074. if (this._isEnabled === value) {
  37075. return;
  37076. }
  37077. this._isEnabled = value;
  37078. this._updateParameters();
  37079. },
  37080. enumerable: true,
  37081. configurable: true
  37082. });
  37083. /**
  37084. * Method called each time the image processing information changes requires to recompile the effect.
  37085. */
  37086. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37087. this.onUpdateParameters.notifyObservers(this);
  37088. };
  37089. ImageProcessingConfiguration.prototype.getClassName = function () {
  37090. return "ImageProcessingConfiguration";
  37091. };
  37092. /**
  37093. * Prepare the list of uniforms associated with the Image Processing effects.
  37094. * @param uniformsList The list of uniforms used in the effect
  37095. * @param defines the list of defines currently in use
  37096. */
  37097. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37098. if (defines.EXPOSURE) {
  37099. uniforms.push("exposureLinear");
  37100. }
  37101. if (defines.CONTRAST) {
  37102. uniforms.push("contrast");
  37103. }
  37104. if (defines.COLORGRADING) {
  37105. uniforms.push("colorTransformSettings");
  37106. }
  37107. if (defines.VIGNETTE) {
  37108. uniforms.push("vInverseScreenSize");
  37109. uniforms.push("vignetteSettings1");
  37110. uniforms.push("vignetteSettings2");
  37111. }
  37112. if (defines.COLORCURVES) {
  37113. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37114. }
  37115. };
  37116. /**
  37117. * Prepare the list of samplers associated with the Image Processing effects.
  37118. * @param uniformsList The list of uniforms used in the effect
  37119. * @param defines the list of defines currently in use
  37120. */
  37121. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37122. if (defines.COLORGRADING) {
  37123. samplersList.push("txColorTransform");
  37124. }
  37125. };
  37126. /**
  37127. * Prepare the list of defines associated to the shader.
  37128. * @param defines the list of defines to complete
  37129. */
  37130. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37131. if (forPostProcess === void 0) { forPostProcess = false; }
  37132. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37133. defines.VIGNETTE = false;
  37134. defines.TONEMAPPING = false;
  37135. defines.CONTRAST = false;
  37136. defines.EXPOSURE = false;
  37137. defines.COLORCURVES = false;
  37138. defines.COLORGRADING = false;
  37139. defines.COLORGRADING3D = false;
  37140. defines.IMAGEPROCESSING = false;
  37141. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37142. return;
  37143. }
  37144. defines.VIGNETTE = this.vignetteEnabled;
  37145. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37146. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37147. defines.TONEMAPPING = this.toneMappingEnabled;
  37148. defines.CONTRAST = (this.contrast !== 1.0);
  37149. defines.EXPOSURE = (this.exposure !== 1.0);
  37150. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37151. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37152. if (defines.COLORGRADING) {
  37153. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37154. }
  37155. else {
  37156. defines.COLORGRADING3D = false;
  37157. }
  37158. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37159. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37160. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37161. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  37162. };
  37163. /**
  37164. * Returns true if all the image processing information are ready.
  37165. */
  37166. ImageProcessingConfiguration.prototype.isReady = function () {
  37167. // Color Grading texure can not be none blocking.
  37168. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37169. };
  37170. /**
  37171. * Binds the image processing to the shader.
  37172. * @param effect The effect to bind to
  37173. */
  37174. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37175. if (aspectRatio === void 0) { aspectRatio = 1; }
  37176. // Color Curves
  37177. if (this._colorCurvesEnabled && this.colorCurves) {
  37178. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37179. }
  37180. // Vignette
  37181. if (this._vignetteEnabled) {
  37182. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37183. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37184. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37185. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37186. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37187. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37188. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37189. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37190. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37191. var vignettePower = -2.0 * this.vignetteWeight;
  37192. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37193. }
  37194. // Exposure
  37195. effect.setFloat("exposureLinear", this.exposure);
  37196. // Contrast
  37197. effect.setFloat("contrast", this.contrast);
  37198. // Color transform settings
  37199. if (this.colorGradingTexture) {
  37200. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37201. var textureSize = this.colorGradingTexture.getSize().height;
  37202. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37203. 0.5 / textureSize, // textureOffset
  37204. textureSize, // textureSize
  37205. this.colorGradingTexture.level // weight
  37206. );
  37207. }
  37208. };
  37209. /**
  37210. * Clones the current image processing instance.
  37211. * @return The cloned image processing
  37212. */
  37213. ImageProcessingConfiguration.prototype.clone = function () {
  37214. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37215. };
  37216. /**
  37217. * Serializes the current image processing instance to a json representation.
  37218. * @return a JSON representation
  37219. */
  37220. ImageProcessingConfiguration.prototype.serialize = function () {
  37221. return BABYLON.SerializationHelper.Serialize(this);
  37222. };
  37223. /**
  37224. * Parses the image processing from a json representation.
  37225. * @param source the JSON source to parse
  37226. * @return The parsed image processing
  37227. */
  37228. ImageProcessingConfiguration.Parse = function (source) {
  37229. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37230. };
  37231. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  37232. /**
  37233. * Used to apply the vignette as a mix with the pixel color.
  37234. */
  37235. get: function () {
  37236. return this._VIGNETTEMODE_MULTIPLY;
  37237. },
  37238. enumerable: true,
  37239. configurable: true
  37240. });
  37241. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  37242. /**
  37243. * Used to apply the vignette as a replacement of the pixel color.
  37244. */
  37245. get: function () {
  37246. return this._VIGNETTEMODE_OPAQUE;
  37247. },
  37248. enumerable: true,
  37249. configurable: true
  37250. });
  37251. // Static constants associated to the image processing.
  37252. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  37253. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  37254. __decorate([
  37255. BABYLON.serializeAsColorCurves()
  37256. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  37257. __decorate([
  37258. BABYLON.serialize()
  37259. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  37260. __decorate([
  37261. BABYLON.serializeAsTexture()
  37262. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  37263. __decorate([
  37264. BABYLON.serialize()
  37265. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  37266. __decorate([
  37267. BABYLON.serialize()
  37268. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  37269. __decorate([
  37270. BABYLON.serialize()
  37271. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  37272. __decorate([
  37273. BABYLON.serialize()
  37274. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  37275. __decorate([
  37276. BABYLON.serialize()
  37277. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  37278. __decorate([
  37279. BABYLON.serialize()
  37280. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  37281. __decorate([
  37282. BABYLON.serialize()
  37283. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  37284. __decorate([
  37285. BABYLON.serialize()
  37286. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  37287. __decorate([
  37288. BABYLON.serialize()
  37289. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  37290. __decorate([
  37291. BABYLON.serialize()
  37292. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  37293. __decorate([
  37294. BABYLON.serializeAsColor4()
  37295. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  37296. __decorate([
  37297. BABYLON.serialize()
  37298. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  37299. __decorate([
  37300. BABYLON.serialize()
  37301. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  37302. __decorate([
  37303. BABYLON.serialize()
  37304. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  37305. __decorate([
  37306. BABYLON.serialize()
  37307. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  37308. __decorate([
  37309. BABYLON.serialize()
  37310. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  37311. return ImageProcessingConfiguration;
  37312. }());
  37313. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  37314. })(BABYLON || (BABYLON = {}));
  37315. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  37316. var BABYLON;
  37317. (function (BABYLON) {
  37318. /**
  37319. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  37320. * It can help converting any input color in a desired output one. This can then be used to create effects
  37321. * from sepia, black and white to sixties or futuristic rendering...
  37322. *
  37323. * The only supported format is currently 3dl.
  37324. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  37325. */
  37326. var ColorGradingTexture = /** @class */ (function (_super) {
  37327. __extends(ColorGradingTexture, _super);
  37328. /**
  37329. * Instantiates a ColorGradingTexture from the following parameters.
  37330. *
  37331. * @param url The location of the color gradind data (currently only supporting 3dl)
  37332. * @param scene The scene the texture will be used in
  37333. */
  37334. function ColorGradingTexture(url, scene) {
  37335. var _this = _super.call(this, scene) || this;
  37336. if (!url) {
  37337. return _this;
  37338. }
  37339. _this._engine = scene.getEngine();
  37340. _this._textureMatrix = BABYLON.Matrix.Identity();
  37341. _this.name = url;
  37342. _this.url = url;
  37343. _this.hasAlpha = false;
  37344. _this.isCube = false;
  37345. _this.is3D = _this._engine.webGLVersion > 1;
  37346. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37347. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37348. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37349. _this.anisotropicFilteringLevel = 1;
  37350. _this._texture = _this._getFromCache(url, true);
  37351. if (!_this._texture) {
  37352. if (!scene.useDelayedTextureLoading) {
  37353. _this.loadTexture();
  37354. }
  37355. else {
  37356. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  37357. }
  37358. }
  37359. return _this;
  37360. }
  37361. /**
  37362. * Returns the texture matrix used in most of the material.
  37363. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  37364. */
  37365. ColorGradingTexture.prototype.getTextureMatrix = function () {
  37366. return this._textureMatrix;
  37367. };
  37368. /**
  37369. * Occurs when the file being loaded is a .3dl LUT file.
  37370. */
  37371. ColorGradingTexture.prototype.load3dlTexture = function () {
  37372. var engine = this._engine;
  37373. var texture;
  37374. if (engine.webGLVersion === 1) {
  37375. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37376. }
  37377. else {
  37378. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37379. }
  37380. this._texture = texture;
  37381. var callback = function (text) {
  37382. if (typeof text !== "string") {
  37383. return;
  37384. }
  37385. var data = null;
  37386. var tempData = null;
  37387. var line;
  37388. var lines = text.split('\n');
  37389. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  37390. var maxColor = 0;
  37391. for (var i = 0; i < lines.length; i++) {
  37392. line = lines[i];
  37393. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  37394. continue;
  37395. if (line.indexOf('#') === 0)
  37396. continue;
  37397. var words = line.split(" ");
  37398. if (size === 0) {
  37399. // Number of space + one
  37400. size = words.length;
  37401. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  37402. tempData = new Float32Array(size * size * size * 4);
  37403. continue;
  37404. }
  37405. if (size != 0) {
  37406. var r = Math.max(parseInt(words[0]), 0);
  37407. var g = Math.max(parseInt(words[1]), 0);
  37408. var b = Math.max(parseInt(words[2]), 0);
  37409. maxColor = Math.max(r, maxColor);
  37410. maxColor = Math.max(g, maxColor);
  37411. maxColor = Math.max(b, maxColor);
  37412. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  37413. if (tempData) {
  37414. tempData[pixelStorageIndex + 0] = r;
  37415. tempData[pixelStorageIndex + 1] = g;
  37416. tempData[pixelStorageIndex + 2] = b;
  37417. }
  37418. pixelIndexSlice++;
  37419. if (pixelIndexSlice % size == 0) {
  37420. pixelIndexH++;
  37421. pixelIndexSlice = 0;
  37422. if (pixelIndexH % size == 0) {
  37423. pixelIndexW++;
  37424. pixelIndexH = 0;
  37425. }
  37426. }
  37427. }
  37428. }
  37429. if (tempData && data) {
  37430. for (var i = 0; i < tempData.length; i++) {
  37431. if (i > 0 && (i + 1) % 4 === 0) {
  37432. data[i] = 255;
  37433. }
  37434. else {
  37435. var value = tempData[i];
  37436. data[i] = (value / maxColor * 255);
  37437. }
  37438. }
  37439. }
  37440. if (texture.is3D) {
  37441. texture.updateSize(size, size, size);
  37442. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37443. }
  37444. else {
  37445. texture.updateSize(size * size, size);
  37446. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37447. }
  37448. };
  37449. var scene = this.getScene();
  37450. if (scene) {
  37451. scene._loadFile(this.url, callback);
  37452. }
  37453. else {
  37454. this._engine._loadFile(this.url, callback);
  37455. }
  37456. return this._texture;
  37457. };
  37458. /**
  37459. * Starts the loading process of the texture.
  37460. */
  37461. ColorGradingTexture.prototype.loadTexture = function () {
  37462. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  37463. this.load3dlTexture();
  37464. }
  37465. };
  37466. /**
  37467. * Clones the color gradind texture.
  37468. */
  37469. ColorGradingTexture.prototype.clone = function () {
  37470. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  37471. // Base texture
  37472. newTexture.level = this.level;
  37473. return newTexture;
  37474. };
  37475. /**
  37476. * Called during delayed load for textures.
  37477. */
  37478. ColorGradingTexture.prototype.delayLoad = function () {
  37479. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  37480. return;
  37481. }
  37482. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  37483. this._texture = this._getFromCache(this.url, true);
  37484. if (!this._texture) {
  37485. this.loadTexture();
  37486. }
  37487. };
  37488. /**
  37489. * Parses a color grading texture serialized by Babylon.
  37490. * @param parsedTexture The texture information being parsedTexture
  37491. * @param scene The scene to load the texture in
  37492. * @param rootUrl The root url of the data assets to load
  37493. * @return A color gradind texture
  37494. */
  37495. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  37496. var texture = null;
  37497. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  37498. texture = new ColorGradingTexture(parsedTexture.name, scene);
  37499. texture.name = parsedTexture.name;
  37500. texture.level = parsedTexture.level;
  37501. }
  37502. return texture;
  37503. };
  37504. /**
  37505. * Serializes the LUT texture to json format.
  37506. */
  37507. ColorGradingTexture.prototype.serialize = function () {
  37508. if (!this.name) {
  37509. return null;
  37510. }
  37511. var serializationObject = {};
  37512. serializationObject.name = this.name;
  37513. serializationObject.level = this.level;
  37514. serializationObject.customType = "BABYLON.ColorGradingTexture";
  37515. return serializationObject;
  37516. };
  37517. /**
  37518. * Empty line regex stored for GC.
  37519. */
  37520. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  37521. return ColorGradingTexture;
  37522. }(BABYLON.BaseTexture));
  37523. BABYLON.ColorGradingTexture = ColorGradingTexture;
  37524. })(BABYLON || (BABYLON = {}));
  37525. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  37526. var BABYLON;
  37527. (function (BABYLON) {
  37528. /**
  37529. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37530. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37531. * 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;
  37532. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37533. */
  37534. var ColorCurves = /** @class */ (function () {
  37535. function ColorCurves() {
  37536. this._dirty = true;
  37537. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  37538. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  37539. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37540. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  37541. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37542. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  37543. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  37544. this._globalHue = 30;
  37545. this._globalDensity = 0;
  37546. this._globalSaturation = 0;
  37547. this._globalExposure = 0;
  37548. this._highlightsHue = 30;
  37549. this._highlightsDensity = 0;
  37550. this._highlightsSaturation = 0;
  37551. this._highlightsExposure = 0;
  37552. this._midtonesHue = 30;
  37553. this._midtonesDensity = 0;
  37554. this._midtonesSaturation = 0;
  37555. this._midtonesExposure = 0;
  37556. this._shadowsHue = 30;
  37557. this._shadowsDensity = 0;
  37558. this._shadowsSaturation = 0;
  37559. this._shadowsExposure = 0;
  37560. }
  37561. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  37562. /**
  37563. * Gets the global Hue value.
  37564. * 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).
  37565. */
  37566. get: function () {
  37567. return this._globalHue;
  37568. },
  37569. /**
  37570. * Sets the global Hue value.
  37571. * 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).
  37572. */
  37573. set: function (value) {
  37574. this._globalHue = value;
  37575. this._dirty = true;
  37576. },
  37577. enumerable: true,
  37578. configurable: true
  37579. });
  37580. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  37581. /**
  37582. * Gets the global Density value.
  37583. * 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.
  37584. * Values less than zero provide a filter of opposite hue.
  37585. */
  37586. get: function () {
  37587. return this._globalDensity;
  37588. },
  37589. /**
  37590. * Sets the global Density value.
  37591. * 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.
  37592. * Values less than zero provide a filter of opposite hue.
  37593. */
  37594. set: function (value) {
  37595. this._globalDensity = value;
  37596. this._dirty = true;
  37597. },
  37598. enumerable: true,
  37599. configurable: true
  37600. });
  37601. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  37602. /**
  37603. * Gets the global Saturation value.
  37604. * 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.
  37605. */
  37606. get: function () {
  37607. return this._globalSaturation;
  37608. },
  37609. /**
  37610. * Sets the global Saturation value.
  37611. * 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.
  37612. */
  37613. set: function (value) {
  37614. this._globalSaturation = value;
  37615. this._dirty = true;
  37616. },
  37617. enumerable: true,
  37618. configurable: true
  37619. });
  37620. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  37621. /**
  37622. * Gets the highlights Hue value.
  37623. * 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).
  37624. */
  37625. get: function () {
  37626. return this._highlightsHue;
  37627. },
  37628. /**
  37629. * Sets the highlights Hue value.
  37630. * 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).
  37631. */
  37632. set: function (value) {
  37633. this._highlightsHue = value;
  37634. this._dirty = true;
  37635. },
  37636. enumerable: true,
  37637. configurable: true
  37638. });
  37639. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  37640. /**
  37641. * Gets the highlights Density value.
  37642. * 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.
  37643. * Values less than zero provide a filter of opposite hue.
  37644. */
  37645. get: function () {
  37646. return this._highlightsDensity;
  37647. },
  37648. /**
  37649. * Sets the highlights Density value.
  37650. * 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.
  37651. * Values less than zero provide a filter of opposite hue.
  37652. */
  37653. set: function (value) {
  37654. this._highlightsDensity = value;
  37655. this._dirty = true;
  37656. },
  37657. enumerable: true,
  37658. configurable: true
  37659. });
  37660. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  37661. /**
  37662. * Gets the highlights Saturation value.
  37663. * 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.
  37664. */
  37665. get: function () {
  37666. return this._highlightsSaturation;
  37667. },
  37668. /**
  37669. * Sets the highlights Saturation value.
  37670. * 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.
  37671. */
  37672. set: function (value) {
  37673. this._highlightsSaturation = value;
  37674. this._dirty = true;
  37675. },
  37676. enumerable: true,
  37677. configurable: true
  37678. });
  37679. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  37680. /**
  37681. * Gets the highlights Exposure value.
  37682. * 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.
  37683. */
  37684. get: function () {
  37685. return this._highlightsExposure;
  37686. },
  37687. /**
  37688. * Sets the highlights Exposure value.
  37689. * 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.
  37690. */
  37691. set: function (value) {
  37692. this._highlightsExposure = value;
  37693. this._dirty = true;
  37694. },
  37695. enumerable: true,
  37696. configurable: true
  37697. });
  37698. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  37699. /**
  37700. * Gets the midtones Hue value.
  37701. * 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).
  37702. */
  37703. get: function () {
  37704. return this._midtonesHue;
  37705. },
  37706. /**
  37707. * Sets the midtones Hue value.
  37708. * 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).
  37709. */
  37710. set: function (value) {
  37711. this._midtonesHue = value;
  37712. this._dirty = true;
  37713. },
  37714. enumerable: true,
  37715. configurable: true
  37716. });
  37717. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  37718. /**
  37719. * Gets the midtones Density value.
  37720. * 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.
  37721. * Values less than zero provide a filter of opposite hue.
  37722. */
  37723. get: function () {
  37724. return this._midtonesDensity;
  37725. },
  37726. /**
  37727. * Sets the midtones Density value.
  37728. * 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.
  37729. * Values less than zero provide a filter of opposite hue.
  37730. */
  37731. set: function (value) {
  37732. this._midtonesDensity = value;
  37733. this._dirty = true;
  37734. },
  37735. enumerable: true,
  37736. configurable: true
  37737. });
  37738. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  37739. /**
  37740. * Gets the midtones Saturation value.
  37741. * 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.
  37742. */
  37743. get: function () {
  37744. return this._midtonesSaturation;
  37745. },
  37746. /**
  37747. * Sets the midtones Saturation value.
  37748. * 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.
  37749. */
  37750. set: function (value) {
  37751. this._midtonesSaturation = value;
  37752. this._dirty = true;
  37753. },
  37754. enumerable: true,
  37755. configurable: true
  37756. });
  37757. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  37758. /**
  37759. * Gets the midtones Exposure value.
  37760. * 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.
  37761. */
  37762. get: function () {
  37763. return this._midtonesExposure;
  37764. },
  37765. /**
  37766. * Sets the midtones Exposure value.
  37767. * 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.
  37768. */
  37769. set: function (value) {
  37770. this._midtonesExposure = value;
  37771. this._dirty = true;
  37772. },
  37773. enumerable: true,
  37774. configurable: true
  37775. });
  37776. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  37777. /**
  37778. * Gets the shadows Hue value.
  37779. * 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).
  37780. */
  37781. get: function () {
  37782. return this._shadowsHue;
  37783. },
  37784. /**
  37785. * Sets the shadows Hue value.
  37786. * 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).
  37787. */
  37788. set: function (value) {
  37789. this._shadowsHue = value;
  37790. this._dirty = true;
  37791. },
  37792. enumerable: true,
  37793. configurable: true
  37794. });
  37795. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  37796. /**
  37797. * Gets the shadows Density value.
  37798. * 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.
  37799. * Values less than zero provide a filter of opposite hue.
  37800. */
  37801. get: function () {
  37802. return this._shadowsDensity;
  37803. },
  37804. /**
  37805. * Sets the shadows Density value.
  37806. * 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.
  37807. * Values less than zero provide a filter of opposite hue.
  37808. */
  37809. set: function (value) {
  37810. this._shadowsDensity = value;
  37811. this._dirty = true;
  37812. },
  37813. enumerable: true,
  37814. configurable: true
  37815. });
  37816. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  37817. /**
  37818. * Gets the shadows Saturation value.
  37819. * 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.
  37820. */
  37821. get: function () {
  37822. return this._shadowsSaturation;
  37823. },
  37824. /**
  37825. * Sets the shadows Saturation value.
  37826. * 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.
  37827. */
  37828. set: function (value) {
  37829. this._shadowsSaturation = value;
  37830. this._dirty = true;
  37831. },
  37832. enumerable: true,
  37833. configurable: true
  37834. });
  37835. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  37836. /**
  37837. * Gets the shadows Exposure value.
  37838. * 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.
  37839. */
  37840. get: function () {
  37841. return this._shadowsExposure;
  37842. },
  37843. /**
  37844. * Sets the shadows Exposure value.
  37845. * 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.
  37846. */
  37847. set: function (value) {
  37848. this._shadowsExposure = value;
  37849. this._dirty = true;
  37850. },
  37851. enumerable: true,
  37852. configurable: true
  37853. });
  37854. ColorCurves.prototype.getClassName = function () {
  37855. return "ColorCurves";
  37856. };
  37857. /**
  37858. * Binds the color curves to the shader.
  37859. * @param colorCurves The color curve to bind
  37860. * @param effect The effect to bind to
  37861. */
  37862. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  37863. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  37864. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  37865. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  37866. if (colorCurves._dirty) {
  37867. colorCurves._dirty = false;
  37868. // Fill in global info.
  37869. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  37870. // Compute highlights info.
  37871. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  37872. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  37873. // Compute midtones info.
  37874. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  37875. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  37876. // Compute shadows info.
  37877. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  37878. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  37879. // Compute deltas (neutral is midtones).
  37880. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  37881. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  37882. }
  37883. if (effect) {
  37884. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  37885. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  37886. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  37887. }
  37888. };
  37889. /**
  37890. * Prepare the list of uniforms associated with the ColorCurves effects.
  37891. * @param uniformsList The list of uniforms used in the effect
  37892. */
  37893. ColorCurves.PrepareUniforms = function (uniformsList) {
  37894. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  37895. };
  37896. /**
  37897. * Returns color grading data based on a hue, density, saturation and exposure value.
  37898. * @param filterHue The hue of the color filter.
  37899. * @param filterDensity The density of the color filter.
  37900. * @param saturation The saturation.
  37901. * @param exposure The exposure.
  37902. * @param result The result data container.
  37903. */
  37904. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  37905. if (hue == null) {
  37906. return;
  37907. }
  37908. hue = ColorCurves.clamp(hue, 0, 360);
  37909. density = ColorCurves.clamp(density, -100, 100);
  37910. saturation = ColorCurves.clamp(saturation, -100, 100);
  37911. exposure = ColorCurves.clamp(exposure, -100, 100);
  37912. // Remap the slider/config filter density with non-linear mapping and also scale by half
  37913. // so that the maximum filter density is only 50% control. This provides fine control
  37914. // for small values and reasonable range.
  37915. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  37916. density *= 0.5;
  37917. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  37918. if (density < 0) {
  37919. density *= -1;
  37920. hue = (hue + 180) % 360;
  37921. }
  37922. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  37923. result.scaleToRef(2, result);
  37924. result.a = 1 + 0.01 * saturation;
  37925. };
  37926. /**
  37927. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  37928. * @param value The input slider value in range [-100,100].
  37929. * @returns Adjusted value.
  37930. */
  37931. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  37932. value /= 100;
  37933. var x = Math.abs(value);
  37934. x = Math.pow(x, 2);
  37935. if (value < 0) {
  37936. x *= -1;
  37937. }
  37938. x *= 100;
  37939. return x;
  37940. };
  37941. /**
  37942. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  37943. * @param hue The hue (H) input.
  37944. * @param saturation The saturation (S) input.
  37945. * @param brightness The brightness (B) input.
  37946. * @result An RGBA color represented as Vector4.
  37947. */
  37948. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  37949. var h = ColorCurves.clamp(hue, 0, 360);
  37950. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  37951. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  37952. if (s === 0) {
  37953. result.r = v;
  37954. result.g = v;
  37955. result.b = v;
  37956. }
  37957. else {
  37958. // sector 0 to 5
  37959. h /= 60;
  37960. var i = Math.floor(h);
  37961. // fractional part of h
  37962. var f = h - i;
  37963. var p = v * (1 - s);
  37964. var q = v * (1 - s * f);
  37965. var t = v * (1 - s * (1 - f));
  37966. switch (i) {
  37967. case 0:
  37968. result.r = v;
  37969. result.g = t;
  37970. result.b = p;
  37971. break;
  37972. case 1:
  37973. result.r = q;
  37974. result.g = v;
  37975. result.b = p;
  37976. break;
  37977. case 2:
  37978. result.r = p;
  37979. result.g = v;
  37980. result.b = t;
  37981. break;
  37982. case 3:
  37983. result.r = p;
  37984. result.g = q;
  37985. result.b = v;
  37986. break;
  37987. case 4:
  37988. result.r = t;
  37989. result.g = p;
  37990. result.b = v;
  37991. break;
  37992. default:// case 5:
  37993. result.r = v;
  37994. result.g = p;
  37995. result.b = q;
  37996. break;
  37997. }
  37998. }
  37999. result.a = 1;
  38000. };
  38001. /**
  38002. * Returns a value clamped between min and max
  38003. * @param value The value to clamp
  38004. * @param min The minimum of value
  38005. * @param max The maximum of value
  38006. * @returns The clamped value.
  38007. */
  38008. ColorCurves.clamp = function (value, min, max) {
  38009. return Math.min(Math.max(value, min), max);
  38010. };
  38011. /**
  38012. * Clones the current color curve instance.
  38013. * @return The cloned curves
  38014. */
  38015. ColorCurves.prototype.clone = function () {
  38016. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38017. };
  38018. /**
  38019. * Serializes the current color curve instance to a json representation.
  38020. * @return a JSON representation
  38021. */
  38022. ColorCurves.prototype.serialize = function () {
  38023. return BABYLON.SerializationHelper.Serialize(this);
  38024. };
  38025. /**
  38026. * Parses the color curve from a json representation.
  38027. * @param source the JSON source to parse
  38028. * @return The parsed curves
  38029. */
  38030. ColorCurves.Parse = function (source) {
  38031. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38032. };
  38033. __decorate([
  38034. BABYLON.serialize()
  38035. ], ColorCurves.prototype, "_globalHue", void 0);
  38036. __decorate([
  38037. BABYLON.serialize()
  38038. ], ColorCurves.prototype, "_globalDensity", void 0);
  38039. __decorate([
  38040. BABYLON.serialize()
  38041. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38042. __decorate([
  38043. BABYLON.serialize()
  38044. ], ColorCurves.prototype, "_globalExposure", void 0);
  38045. __decorate([
  38046. BABYLON.serialize()
  38047. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38048. __decorate([
  38049. BABYLON.serialize()
  38050. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38051. __decorate([
  38052. BABYLON.serialize()
  38053. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38054. __decorate([
  38055. BABYLON.serialize()
  38056. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38057. __decorate([
  38058. BABYLON.serialize()
  38059. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38060. __decorate([
  38061. BABYLON.serialize()
  38062. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38063. __decorate([
  38064. BABYLON.serialize()
  38065. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38066. __decorate([
  38067. BABYLON.serialize()
  38068. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38069. return ColorCurves;
  38070. }());
  38071. BABYLON.ColorCurves = ColorCurves;
  38072. })(BABYLON || (BABYLON = {}));
  38073. //# sourceMappingURL=babylon.colorCurves.js.map
  38074. //# sourceMappingURL=babylon.behavior.js.map
  38075. var BABYLON;
  38076. (function (BABYLON) {
  38077. /**
  38078. * "Static Class" containing the most commonly used helper while dealing with material for
  38079. * rendering purpose.
  38080. *
  38081. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38082. *
  38083. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38084. */
  38085. var MaterialHelper = /** @class */ (function () {
  38086. function MaterialHelper() {
  38087. }
  38088. /**
  38089. * Bind the current view position to an effect.
  38090. * @param effect The effect to be bound
  38091. * @param scene The scene the eyes position is used from
  38092. */
  38093. MaterialHelper.BindEyePosition = function (effect, scene) {
  38094. if (scene._forcedViewPosition) {
  38095. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38096. return;
  38097. }
  38098. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38099. };
  38100. /**
  38101. * Helps preparing the defines values about the UVs in used in the effect.
  38102. * UVs are shared as much as we can accross chanels in the shaders.
  38103. * @param texture The texture we are preparing the UVs for
  38104. * @param defines The defines to update
  38105. * @param key The chanel key "diffuse", "specular"... used in the shader
  38106. */
  38107. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38108. defines._needUVs = true;
  38109. defines[key] = true;
  38110. if (texture.getTextureMatrix().isIdentity(true)) {
  38111. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38112. if (texture.coordinatesIndex === 0) {
  38113. defines["MAINUV1"] = true;
  38114. }
  38115. else {
  38116. defines["MAINUV2"] = true;
  38117. }
  38118. }
  38119. else {
  38120. defines[key + "DIRECTUV"] = 0;
  38121. }
  38122. };
  38123. /**
  38124. * Binds a texture matrix value to its corrsponding uniform
  38125. * @param texture The texture to bind the matrix for
  38126. * @param uniformBuffer The uniform buffer receivin the data
  38127. * @param key The chanel key "diffuse", "specular"... used in the shader
  38128. */
  38129. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38130. var matrix = texture.getTextureMatrix();
  38131. if (!matrix.isIdentity(true)) {
  38132. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38133. }
  38134. };
  38135. /**
  38136. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38137. * @param mesh defines the current mesh
  38138. * @param scene defines the current scene
  38139. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38140. * @param pointsCloud defines if point cloud rendering has to be turned on
  38141. * @param fogEnabled defines if fog has to be turned on
  38142. * @param alphaTest defines if alpha testing has to be turned on
  38143. * @param defines defines the current list of defines
  38144. */
  38145. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38146. if (defines._areMiscDirty) {
  38147. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38148. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  38149. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38150. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38151. defines["ALPHATEST"] = alphaTest;
  38152. }
  38153. };
  38154. /**
  38155. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38156. * @param scene defines the current scene
  38157. * @param engine defines the current engine
  38158. * @param defines specifies the list of active defines
  38159. * @param useInstances defines if instances have to be turned on
  38160. * @param useClipPlane defines if clip plane have to be turned on
  38161. */
  38162. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38163. if (useClipPlane === void 0) { useClipPlane = null; }
  38164. var changed = false;
  38165. if (useClipPlane == null) {
  38166. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38167. }
  38168. if (defines["CLIPPLANE"] !== useClipPlane) {
  38169. defines["CLIPPLANE"] = useClipPlane;
  38170. changed = true;
  38171. }
  38172. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38173. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38174. changed = true;
  38175. }
  38176. if (defines["INSTANCES"] !== useInstances) {
  38177. defines["INSTANCES"] = useInstances;
  38178. changed = true;
  38179. }
  38180. if (changed) {
  38181. defines.markAsUnprocessed();
  38182. }
  38183. };
  38184. /**
  38185. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38186. * @param mesh The mesh containing the geometry data we will draw
  38187. * @param defines The defines to update
  38188. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38189. * @param useBones Precise whether bones should be used or not (override mesh info)
  38190. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38191. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38192. * @returns false if defines are considered not dirty and have not been checked
  38193. */
  38194. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38195. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38196. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38197. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38198. return false;
  38199. }
  38200. defines._normals = defines._needNormals;
  38201. defines._uvs = defines._needUVs;
  38202. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38203. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38204. defines["TANGENT"] = true;
  38205. }
  38206. if (defines._needUVs) {
  38207. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38208. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38209. }
  38210. else {
  38211. defines["UV1"] = false;
  38212. defines["UV2"] = false;
  38213. }
  38214. if (useVertexColor) {
  38215. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38216. defines["VERTEXCOLOR"] = hasVertexColors;
  38217. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38218. }
  38219. if (useBones) {
  38220. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38221. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  38222. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  38223. }
  38224. else {
  38225. defines["NUM_BONE_INFLUENCERS"] = 0;
  38226. defines["BonesPerMesh"] = 0;
  38227. }
  38228. }
  38229. if (useMorphTargets) {
  38230. var manager = mesh.morphTargetManager;
  38231. if (manager) {
  38232. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  38233. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  38234. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  38235. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  38236. }
  38237. else {
  38238. defines["MORPHTARGETS_TANGENT"] = false;
  38239. defines["MORPHTARGETS_NORMAL"] = false;
  38240. defines["MORPHTARGETS"] = false;
  38241. defines["NUM_MORPH_INFLUENCERS"] = 0;
  38242. }
  38243. }
  38244. return true;
  38245. };
  38246. /**
  38247. * Prepares the defines related to the light information passed in parameter
  38248. * @param scene The scene we are intending to draw
  38249. * @param mesh The mesh the effect is compiling for
  38250. * @param defines The defines to update
  38251. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  38252. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  38253. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  38254. * @returns true if normals will be required for the rest of the effect
  38255. */
  38256. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  38257. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38258. if (disableLighting === void 0) { disableLighting = false; }
  38259. if (!defines._areLightsDirty) {
  38260. return defines._needNormals;
  38261. }
  38262. var lightIndex = 0;
  38263. var needNormals = false;
  38264. var needRebuild = false;
  38265. var lightmapMode = false;
  38266. var shadowEnabled = false;
  38267. var specularEnabled = false;
  38268. if (scene.lightsEnabled && !disableLighting) {
  38269. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  38270. var light = _a[_i];
  38271. needNormals = true;
  38272. if (defines["LIGHT" + lightIndex] === undefined) {
  38273. needRebuild = true;
  38274. }
  38275. defines["LIGHT" + lightIndex] = true;
  38276. defines["SPOTLIGHT" + lightIndex] = false;
  38277. defines["HEMILIGHT" + lightIndex] = false;
  38278. defines["POINTLIGHT" + lightIndex] = false;
  38279. defines["DIRLIGHT" + lightIndex] = false;
  38280. var type;
  38281. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  38282. type = "SPOTLIGHT" + lightIndex;
  38283. var spotLight = light;
  38284. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  38285. }
  38286. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  38287. type = "HEMILIGHT" + lightIndex;
  38288. }
  38289. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  38290. type = "POINTLIGHT" + lightIndex;
  38291. }
  38292. else {
  38293. type = "DIRLIGHT" + lightIndex;
  38294. }
  38295. defines[type] = true;
  38296. // Specular
  38297. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  38298. specularEnabled = true;
  38299. }
  38300. // Shadows
  38301. defines["SHADOW" + lightIndex] = false;
  38302. defines["SHADOWPCF" + lightIndex] = false;
  38303. defines["SHADOWESM" + lightIndex] = false;
  38304. defines["SHADOWCUBE" + lightIndex] = false;
  38305. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  38306. var shadowGenerator = light.getShadowGenerator();
  38307. if (shadowGenerator) {
  38308. shadowEnabled = true;
  38309. shadowGenerator.prepareDefines(defines, lightIndex);
  38310. }
  38311. }
  38312. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  38313. lightmapMode = true;
  38314. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  38315. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  38316. }
  38317. else {
  38318. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  38319. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  38320. }
  38321. lightIndex++;
  38322. if (lightIndex === maxSimultaneousLights)
  38323. break;
  38324. }
  38325. }
  38326. defines["SPECULARTERM"] = specularEnabled;
  38327. defines["SHADOWS"] = shadowEnabled;
  38328. // Resetting all other lights if any
  38329. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  38330. if (defines["LIGHT" + index] !== undefined) {
  38331. defines["LIGHT" + index] = false;
  38332. defines["HEMILIGHT" + lightIndex] = false;
  38333. defines["POINTLIGHT" + lightIndex] = false;
  38334. defines["DIRLIGHT" + lightIndex] = false;
  38335. defines["SPOTLIGHT" + lightIndex] = false;
  38336. defines["SHADOW" + lightIndex] = false;
  38337. }
  38338. }
  38339. var caps = scene.getEngine().getCaps();
  38340. if (defines["SHADOWFLOAT"] === undefined) {
  38341. needRebuild = true;
  38342. }
  38343. defines["SHADOWFLOAT"] = shadowEnabled &&
  38344. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  38345. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  38346. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  38347. if (needRebuild) {
  38348. defines.rebuild();
  38349. }
  38350. return needNormals;
  38351. };
  38352. /**
  38353. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  38354. * that won t be acctive due to defines being turned off.
  38355. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  38356. * @param samplersList The samplers list
  38357. * @param defines The defines helping in the list generation
  38358. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  38359. */
  38360. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  38361. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38362. var uniformsList;
  38363. var uniformBuffersList = null;
  38364. if (uniformsListOrOptions.uniformsNames) {
  38365. var options = uniformsListOrOptions;
  38366. uniformsList = options.uniformsNames;
  38367. uniformBuffersList = options.uniformBuffersNames;
  38368. samplersList = options.samplers;
  38369. defines = options.defines;
  38370. maxSimultaneousLights = options.maxSimultaneousLights;
  38371. }
  38372. else {
  38373. uniformsList = uniformsListOrOptions;
  38374. if (!samplersList) {
  38375. samplersList = [];
  38376. }
  38377. }
  38378. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38379. if (!defines["LIGHT" + lightIndex]) {
  38380. break;
  38381. }
  38382. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  38383. if (uniformBuffersList) {
  38384. uniformBuffersList.push("Light" + lightIndex);
  38385. }
  38386. samplersList.push("shadowSampler" + lightIndex);
  38387. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  38388. samplersList.push("projectionLightSampler" + lightIndex);
  38389. uniformsList.push("textureProjectionMatrix" + lightIndex);
  38390. }
  38391. }
  38392. if (defines["NUM_MORPH_INFLUENCERS"]) {
  38393. uniformsList.push("morphTargetInfluences");
  38394. }
  38395. };
  38396. /**
  38397. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  38398. * @param defines The defines to update while falling back
  38399. * @param fallbacks The authorized effect fallbacks
  38400. * @param maxSimultaneousLights The maximum number of lights allowed
  38401. * @param rank the current rank of the Effect
  38402. * @returns The newly affected rank
  38403. */
  38404. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  38405. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38406. if (rank === void 0) { rank = 0; }
  38407. var lightFallbackRank = 0;
  38408. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38409. if (!defines["LIGHT" + lightIndex]) {
  38410. break;
  38411. }
  38412. if (lightIndex > 0) {
  38413. lightFallbackRank = rank + lightIndex;
  38414. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  38415. }
  38416. if (!defines["SHADOWS"]) {
  38417. if (defines["SHADOW" + lightIndex]) {
  38418. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  38419. }
  38420. if (defines["SHADOWPCF" + lightIndex]) {
  38421. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  38422. }
  38423. if (defines["SHADOWESM" + lightIndex]) {
  38424. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  38425. }
  38426. }
  38427. }
  38428. return lightFallbackRank++;
  38429. };
  38430. /**
  38431. * Prepares the list of attributes required for morph targets according to the effect defines.
  38432. * @param attribs The current list of supported attribs
  38433. * @param mesh The mesh to prepare the morph targets attributes for
  38434. * @param defines The current Defines of the effect
  38435. */
  38436. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  38437. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  38438. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  38439. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  38440. var manager = mesh.morphTargetManager;
  38441. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  38442. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  38443. for (var index = 0; index < influencers; index++) {
  38444. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  38445. if (normal) {
  38446. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  38447. }
  38448. if (tangent) {
  38449. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  38450. }
  38451. if (attribs.length > maxAttributesCount) {
  38452. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  38453. }
  38454. }
  38455. }
  38456. };
  38457. /**
  38458. * Prepares the list of attributes required for bones according to the effect defines.
  38459. * @param attribs The current list of supported attribs
  38460. * @param mesh The mesh to prepare the bones attributes for
  38461. * @param defines The current Defines of the effect
  38462. * @param fallbacks The current efffect fallback strategy
  38463. */
  38464. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  38465. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  38466. fallbacks.addCPUSkinningFallback(0, mesh);
  38467. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38468. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38469. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  38470. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38471. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38472. }
  38473. }
  38474. };
  38475. /**
  38476. * Prepares the list of attributes required for instances according to the effect defines.
  38477. * @param attribs The current list of supported attribs
  38478. * @param defines The current Defines of the effect
  38479. */
  38480. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  38481. if (defines["INSTANCES"]) {
  38482. attribs.push("world0");
  38483. attribs.push("world1");
  38484. attribs.push("world2");
  38485. attribs.push("world3");
  38486. }
  38487. };
  38488. /**
  38489. * Binds the light shadow information to the effect for the given mesh.
  38490. * @param light The light containing the generator
  38491. * @param scene The scene the lights belongs to
  38492. * @param mesh The mesh we are binding the information to render
  38493. * @param lightIndex The light index in the effect used to render the mesh
  38494. * @param effect The effect we are binding the data to
  38495. */
  38496. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  38497. if (light.shadowEnabled && mesh.receiveShadows) {
  38498. var shadowGenerator = light.getShadowGenerator();
  38499. if (shadowGenerator) {
  38500. shadowGenerator.bindShadowLight(lightIndex, effect);
  38501. }
  38502. }
  38503. };
  38504. /**
  38505. * Binds the light information to the effect.
  38506. * @param light The light containing the generator
  38507. * @param effect The effect we are binding the data to
  38508. * @param lightIndex The light index in the effect used to render
  38509. */
  38510. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  38511. light.transferToEffect(effect, lightIndex + "");
  38512. };
  38513. /**
  38514. * Binds the lights information from the scene to the effect for the given mesh.
  38515. * @param scene The scene the lights belongs to
  38516. * @param mesh The mesh we are binding the information to render
  38517. * @param effect The effect we are binding the data to
  38518. * @param defines The generated defines for the effect
  38519. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  38520. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  38521. */
  38522. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  38523. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38524. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  38525. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  38526. for (var i = 0; i < len; i++) {
  38527. var light = mesh._lightSources[i];
  38528. var iAsString = i.toString();
  38529. var scaledIntensity = light.getScaledIntensity();
  38530. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  38531. MaterialHelper.BindLightProperties(light, effect, i);
  38532. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  38533. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  38534. if (defines["SPECULARTERM"]) {
  38535. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  38536. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  38537. }
  38538. // Shadows
  38539. if (scene.shadowsEnabled) {
  38540. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  38541. }
  38542. light._uniformBuffer.update();
  38543. }
  38544. };
  38545. /**
  38546. * Binds the fog information from the scene to the effect for the given mesh.
  38547. * @param scene The scene the lights belongs to
  38548. * @param mesh The mesh we are binding the information to render
  38549. * @param effect The effect we are binding the data to
  38550. */
  38551. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  38552. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  38553. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  38554. effect.setColor3("vFogColor", scene.fogColor);
  38555. }
  38556. };
  38557. /**
  38558. * Binds the bones information from the mesh to the effect.
  38559. * @param mesh The mesh we are binding the information to render
  38560. * @param effect The effect we are binding the data to
  38561. */
  38562. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  38563. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38564. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  38565. if (matrices && effect) {
  38566. effect.setMatrices("mBones", matrices);
  38567. }
  38568. }
  38569. };
  38570. /**
  38571. * Binds the morph targets information from the mesh to the effect.
  38572. * @param abstractMesh The mesh we are binding the information to render
  38573. * @param effect The effect we are binding the data to
  38574. */
  38575. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  38576. var manager = abstractMesh.morphTargetManager;
  38577. if (!abstractMesh || !manager) {
  38578. return;
  38579. }
  38580. effect.setFloatArray("morphTargetInfluences", manager.influences);
  38581. };
  38582. /**
  38583. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  38584. * @param defines The generated defines used in the effect
  38585. * @param effect The effect we are binding the data to
  38586. * @param scene The scene we are willing to render with logarithmic scale for
  38587. */
  38588. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  38589. if (defines["LOGARITHMICDEPTH"]) {
  38590. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  38591. }
  38592. };
  38593. /**
  38594. * Binds the clip plane information from the scene to the effect.
  38595. * @param scene The scene the clip plane information are extracted from
  38596. * @param effect The effect we are binding the data to
  38597. */
  38598. MaterialHelper.BindClipPlane = function (effect, scene) {
  38599. if (scene.clipPlane) {
  38600. var clipPlane = scene.clipPlane;
  38601. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  38602. }
  38603. };
  38604. return MaterialHelper;
  38605. }());
  38606. BABYLON.MaterialHelper = MaterialHelper;
  38607. })(BABYLON || (BABYLON = {}));
  38608. //# sourceMappingURL=babylon.materialHelper.js.map
  38609. var BABYLON;
  38610. (function (BABYLON) {
  38611. var PushMaterial = /** @class */ (function (_super) {
  38612. __extends(PushMaterial, _super);
  38613. function PushMaterial(name, scene) {
  38614. var _this = _super.call(this, name, scene) || this;
  38615. _this._normalMatrix = new BABYLON.Matrix();
  38616. _this.storeEffectOnSubMeshes = true;
  38617. return _this;
  38618. }
  38619. PushMaterial.prototype.getEffect = function () {
  38620. return this._activeEffect;
  38621. };
  38622. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  38623. if (!mesh) {
  38624. return false;
  38625. }
  38626. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  38627. return true;
  38628. }
  38629. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  38630. };
  38631. /**
  38632. * Binds the given world matrix to the active effect
  38633. *
  38634. * @param world the matrix to bind
  38635. */
  38636. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38637. this._activeEffect.setMatrix("world", world);
  38638. };
  38639. /**
  38640. * Binds the given normal matrix to the active effect
  38641. *
  38642. * @param normalMatrix the matrix to bind
  38643. */
  38644. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  38645. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  38646. };
  38647. PushMaterial.prototype.bind = function (world, mesh) {
  38648. if (!mesh) {
  38649. return;
  38650. }
  38651. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  38652. };
  38653. PushMaterial.prototype._afterBind = function (mesh, effect) {
  38654. if (effect === void 0) { effect = null; }
  38655. _super.prototype._afterBind.call(this, mesh);
  38656. this.getScene()._cachedEffect = effect;
  38657. };
  38658. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  38659. if (visibility === void 0) { visibility = 1; }
  38660. return scene.isCachedMaterialInvalid(this, effect, visibility);
  38661. };
  38662. return PushMaterial;
  38663. }(BABYLON.Material));
  38664. BABYLON.PushMaterial = PushMaterial;
  38665. })(BABYLON || (BABYLON = {}));
  38666. //# sourceMappingURL=babylon.pushMaterial.js.map
  38667. var BABYLON;
  38668. (function (BABYLON) {
  38669. /** @ignore */
  38670. var StandardMaterialDefines = /** @class */ (function (_super) {
  38671. __extends(StandardMaterialDefines, _super);
  38672. function StandardMaterialDefines() {
  38673. var _this = _super.call(this) || this;
  38674. _this.MAINUV1 = false;
  38675. _this.MAINUV2 = false;
  38676. _this.DIFFUSE = false;
  38677. _this.DIFFUSEDIRECTUV = 0;
  38678. _this.AMBIENT = false;
  38679. _this.AMBIENTDIRECTUV = 0;
  38680. _this.OPACITY = false;
  38681. _this.OPACITYDIRECTUV = 0;
  38682. _this.OPACITYRGB = false;
  38683. _this.REFLECTION = false;
  38684. _this.EMISSIVE = false;
  38685. _this.EMISSIVEDIRECTUV = 0;
  38686. _this.SPECULAR = false;
  38687. _this.SPECULARDIRECTUV = 0;
  38688. _this.BUMP = false;
  38689. _this.BUMPDIRECTUV = 0;
  38690. _this.PARALLAX = false;
  38691. _this.PARALLAXOCCLUSION = false;
  38692. _this.SPECULAROVERALPHA = false;
  38693. _this.CLIPPLANE = false;
  38694. _this.ALPHATEST = false;
  38695. _this.DEPTHPREPASS = false;
  38696. _this.ALPHAFROMDIFFUSE = false;
  38697. _this.POINTSIZE = false;
  38698. _this.FOG = false;
  38699. _this.SPECULARTERM = false;
  38700. _this.DIFFUSEFRESNEL = false;
  38701. _this.OPACITYFRESNEL = false;
  38702. _this.REFLECTIONFRESNEL = false;
  38703. _this.REFRACTIONFRESNEL = false;
  38704. _this.EMISSIVEFRESNEL = false;
  38705. _this.FRESNEL = false;
  38706. _this.NORMAL = false;
  38707. _this.UV1 = false;
  38708. _this.UV2 = false;
  38709. _this.VERTEXCOLOR = false;
  38710. _this.VERTEXALPHA = false;
  38711. _this.NUM_BONE_INFLUENCERS = 0;
  38712. _this.BonesPerMesh = 0;
  38713. _this.INSTANCES = false;
  38714. _this.GLOSSINESS = false;
  38715. _this.ROUGHNESS = false;
  38716. _this.EMISSIVEASILLUMINATION = false;
  38717. _this.LINKEMISSIVEWITHDIFFUSE = false;
  38718. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  38719. _this.LIGHTMAP = false;
  38720. _this.LIGHTMAPDIRECTUV = 0;
  38721. _this.OBJECTSPACE_NORMALMAP = false;
  38722. _this.USELIGHTMAPASSHADOWMAP = false;
  38723. _this.REFLECTIONMAP_3D = false;
  38724. _this.REFLECTIONMAP_SPHERICAL = false;
  38725. _this.REFLECTIONMAP_PLANAR = false;
  38726. _this.REFLECTIONMAP_CUBIC = false;
  38727. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  38728. _this.REFLECTIONMAP_PROJECTION = false;
  38729. _this.REFLECTIONMAP_SKYBOX = false;
  38730. _this.REFLECTIONMAP_EXPLICIT = false;
  38731. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38732. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38733. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38734. _this.INVERTCUBICMAP = false;
  38735. _this.LOGARITHMICDEPTH = false;
  38736. _this.REFRACTION = false;
  38737. _this.REFRACTIONMAP_3D = false;
  38738. _this.REFLECTIONOVERALPHA = false;
  38739. _this.TWOSIDEDLIGHTING = false;
  38740. _this.SHADOWFLOAT = false;
  38741. _this.MORPHTARGETS = false;
  38742. _this.MORPHTARGETS_NORMAL = false;
  38743. _this.MORPHTARGETS_TANGENT = false;
  38744. _this.NUM_MORPH_INFLUENCERS = 0;
  38745. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  38746. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  38747. _this.IMAGEPROCESSING = false;
  38748. _this.VIGNETTE = false;
  38749. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  38750. _this.VIGNETTEBLENDMODEOPAQUE = false;
  38751. _this.TONEMAPPING = false;
  38752. _this.CONTRAST = false;
  38753. _this.COLORCURVES = false;
  38754. _this.COLORGRADING = false;
  38755. _this.COLORGRADING3D = false;
  38756. _this.SAMPLER3DGREENDEPTH = false;
  38757. _this.SAMPLER3DBGRMAP = false;
  38758. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  38759. _this.EXPOSURE = false;
  38760. _this.rebuild();
  38761. return _this;
  38762. }
  38763. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  38764. var modes = [
  38765. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  38766. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  38767. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  38768. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  38769. ];
  38770. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  38771. var mode = modes_1[_i];
  38772. this[mode] = (mode === modeToEnable);
  38773. }
  38774. };
  38775. return StandardMaterialDefines;
  38776. }(BABYLON.MaterialDefines));
  38777. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  38778. var StandardMaterial = /** @class */ (function (_super) {
  38779. __extends(StandardMaterial, _super);
  38780. function StandardMaterial(name, scene) {
  38781. var _this = _super.call(this, name, scene) || this;
  38782. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  38783. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  38784. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  38785. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38786. _this.specularPower = 64;
  38787. _this._useAlphaFromDiffuseTexture = false;
  38788. _this._useEmissiveAsIllumination = false;
  38789. _this._linkEmissiveWithDiffuse = false;
  38790. _this._useSpecularOverAlpha = false;
  38791. _this._useReflectionOverAlpha = false;
  38792. _this._disableLighting = false;
  38793. _this._useObjectSpaceNormalMap = false;
  38794. _this._useParallax = false;
  38795. _this._useParallaxOcclusion = false;
  38796. _this.parallaxScaleBias = 0.05;
  38797. _this._roughness = 0;
  38798. _this.indexOfRefraction = 0.98;
  38799. _this.invertRefractionY = true;
  38800. _this._useLightmapAsShadowmap = false;
  38801. _this._useReflectionFresnelFromSpecular = false;
  38802. _this._useGlossinessFromSpecularMapAlpha = false;
  38803. _this._maxSimultaneousLights = 4;
  38804. /**
  38805. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38806. */
  38807. _this._invertNormalMapX = false;
  38808. /**
  38809. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38810. */
  38811. _this._invertNormalMapY = false;
  38812. /**
  38813. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38814. */
  38815. _this._twoSidedLighting = false;
  38816. _this._renderTargets = new BABYLON.SmartArray(16);
  38817. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  38818. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  38819. // Setup the default processing configuration to the scene.
  38820. _this._attachImageProcessingConfiguration(null);
  38821. _this.getRenderTargetTextures = function () {
  38822. _this._renderTargets.reset();
  38823. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  38824. _this._renderTargets.push(_this._reflectionTexture);
  38825. }
  38826. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  38827. _this._renderTargets.push(_this._refractionTexture);
  38828. }
  38829. return _this._renderTargets;
  38830. };
  38831. return _this;
  38832. }
  38833. ;
  38834. ;
  38835. ;
  38836. ;
  38837. ;
  38838. ;
  38839. ;
  38840. ;
  38841. ;
  38842. ;
  38843. ;
  38844. ;
  38845. ;
  38846. ;
  38847. ;
  38848. ;
  38849. ;
  38850. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  38851. /**
  38852. * Gets the image processing configuration used either in this material.
  38853. */
  38854. get: function () {
  38855. return this._imageProcessingConfiguration;
  38856. },
  38857. /**
  38858. * Sets the Default image processing configuration used either in the this material.
  38859. *
  38860. * If sets to null, the scene one is in use.
  38861. */
  38862. set: function (value) {
  38863. this._attachImageProcessingConfiguration(value);
  38864. // Ensure the effect will be rebuilt.
  38865. this._markAllSubMeshesAsTexturesDirty();
  38866. },
  38867. enumerable: true,
  38868. configurable: true
  38869. });
  38870. /**
  38871. * Attaches a new image processing configuration to the Standard Material.
  38872. * @param configuration
  38873. */
  38874. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  38875. var _this = this;
  38876. if (configuration === this._imageProcessingConfiguration) {
  38877. return;
  38878. }
  38879. // Detaches observer.
  38880. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38881. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38882. }
  38883. // Pick the scene configuration if needed.
  38884. if (!configuration) {
  38885. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  38886. }
  38887. else {
  38888. this._imageProcessingConfiguration = configuration;
  38889. }
  38890. // Attaches observer.
  38891. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  38892. _this._markAllSubMeshesAsImageProcessingDirty();
  38893. });
  38894. };
  38895. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  38896. /**
  38897. * Gets wether the color curves effect is enabled.
  38898. */
  38899. get: function () {
  38900. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38901. },
  38902. /**
  38903. * Sets wether the color curves effect is enabled.
  38904. */
  38905. set: function (value) {
  38906. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38907. },
  38908. enumerable: true,
  38909. configurable: true
  38910. });
  38911. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  38912. /**
  38913. * Gets wether the color grading effect is enabled.
  38914. */
  38915. get: function () {
  38916. return this.imageProcessingConfiguration.colorGradingEnabled;
  38917. },
  38918. /**
  38919. * Gets wether the color grading effect is enabled.
  38920. */
  38921. set: function (value) {
  38922. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38923. },
  38924. enumerable: true,
  38925. configurable: true
  38926. });
  38927. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  38928. /**
  38929. * Gets wether tonemapping is enabled or not.
  38930. */
  38931. get: function () {
  38932. return this._imageProcessingConfiguration.toneMappingEnabled;
  38933. },
  38934. /**
  38935. * Sets wether tonemapping is enabled or not
  38936. */
  38937. set: function (value) {
  38938. this._imageProcessingConfiguration.toneMappingEnabled = value;
  38939. },
  38940. enumerable: true,
  38941. configurable: true
  38942. });
  38943. ;
  38944. ;
  38945. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  38946. /**
  38947. * The camera exposure used on this material.
  38948. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38949. * This corresponds to a photographic exposure.
  38950. */
  38951. get: function () {
  38952. return this._imageProcessingConfiguration.exposure;
  38953. },
  38954. /**
  38955. * The camera exposure used on this material.
  38956. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38957. * This corresponds to a photographic exposure.
  38958. */
  38959. set: function (value) {
  38960. this._imageProcessingConfiguration.exposure = value;
  38961. },
  38962. enumerable: true,
  38963. configurable: true
  38964. });
  38965. ;
  38966. ;
  38967. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  38968. /**
  38969. * Gets The camera contrast used on this material.
  38970. */
  38971. get: function () {
  38972. return this._imageProcessingConfiguration.contrast;
  38973. },
  38974. /**
  38975. * Sets The camera contrast used on this material.
  38976. */
  38977. set: function (value) {
  38978. this._imageProcessingConfiguration.contrast = value;
  38979. },
  38980. enumerable: true,
  38981. configurable: true
  38982. });
  38983. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  38984. /**
  38985. * Gets the Color Grading 2D Lookup Texture.
  38986. */
  38987. get: function () {
  38988. return this._imageProcessingConfiguration.colorGradingTexture;
  38989. },
  38990. /**
  38991. * Sets the Color Grading 2D Lookup Texture.
  38992. */
  38993. set: function (value) {
  38994. this._imageProcessingConfiguration.colorGradingTexture = value;
  38995. },
  38996. enumerable: true,
  38997. configurable: true
  38998. });
  38999. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39000. /**
  39001. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39002. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39003. * 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;
  39004. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39005. */
  39006. get: function () {
  39007. return this._imageProcessingConfiguration.colorCurves;
  39008. },
  39009. /**
  39010. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39011. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39012. * 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;
  39013. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39014. */
  39015. set: function (value) {
  39016. this._imageProcessingConfiguration.colorCurves = value;
  39017. },
  39018. enumerable: true,
  39019. configurable: true
  39020. });
  39021. StandardMaterial.prototype.getClassName = function () {
  39022. return "StandardMaterial";
  39023. };
  39024. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39025. get: function () {
  39026. return this._useLogarithmicDepth;
  39027. },
  39028. set: function (value) {
  39029. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39030. this._markAllSubMeshesAsMiscDirty();
  39031. },
  39032. enumerable: true,
  39033. configurable: true
  39034. });
  39035. StandardMaterial.prototype.needAlphaBlending = function () {
  39036. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39037. };
  39038. StandardMaterial.prototype.needAlphaTesting = function () {
  39039. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39040. };
  39041. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39042. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39043. };
  39044. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39045. return this._diffuseTexture;
  39046. };
  39047. /**
  39048. * Child classes can use it to update shaders
  39049. */
  39050. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39051. if (useInstances === void 0) { useInstances = false; }
  39052. if (subMesh.effect && this.isFrozen) {
  39053. if (this._wasPreviouslyReady && subMesh.effect) {
  39054. return true;
  39055. }
  39056. }
  39057. if (!subMesh._materialDefines) {
  39058. subMesh._materialDefines = new StandardMaterialDefines();
  39059. }
  39060. var scene = this.getScene();
  39061. var defines = subMesh._materialDefines;
  39062. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39063. if (defines._renderId === scene.getRenderId()) {
  39064. return true;
  39065. }
  39066. }
  39067. var engine = scene.getEngine();
  39068. // Lights
  39069. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39070. // Textures
  39071. if (defines._areTexturesDirty) {
  39072. defines._needUVs = false;
  39073. defines.MAINUV1 = false;
  39074. defines.MAINUV2 = false;
  39075. if (scene.texturesEnabled) {
  39076. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39077. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39078. return false;
  39079. }
  39080. else {
  39081. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39082. }
  39083. }
  39084. else {
  39085. defines.DIFFUSE = false;
  39086. }
  39087. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39088. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39089. return false;
  39090. }
  39091. else {
  39092. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39093. }
  39094. }
  39095. else {
  39096. defines.AMBIENT = false;
  39097. }
  39098. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39099. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39100. return false;
  39101. }
  39102. else {
  39103. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39104. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39105. }
  39106. }
  39107. else {
  39108. defines.OPACITY = false;
  39109. }
  39110. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39111. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39112. return false;
  39113. }
  39114. else {
  39115. defines._needNormals = true;
  39116. defines.REFLECTION = true;
  39117. defines.ROUGHNESS = (this._roughness > 0);
  39118. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39119. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39120. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39121. switch (this._reflectionTexture.coordinatesMode) {
  39122. case BABYLON.Texture.CUBIC_MODE:
  39123. case BABYLON.Texture.INVCUBIC_MODE:
  39124. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39125. break;
  39126. case BABYLON.Texture.EXPLICIT_MODE:
  39127. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39128. break;
  39129. case BABYLON.Texture.PLANAR_MODE:
  39130. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39131. break;
  39132. case BABYLON.Texture.PROJECTION_MODE:
  39133. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39134. break;
  39135. case BABYLON.Texture.SKYBOX_MODE:
  39136. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39137. break;
  39138. case BABYLON.Texture.SPHERICAL_MODE:
  39139. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39140. break;
  39141. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39142. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39143. break;
  39144. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39145. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39146. break;
  39147. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39148. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39149. break;
  39150. }
  39151. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39152. }
  39153. }
  39154. else {
  39155. defines.REFLECTION = false;
  39156. }
  39157. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39158. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39159. return false;
  39160. }
  39161. else {
  39162. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39163. }
  39164. }
  39165. else {
  39166. defines.EMISSIVE = false;
  39167. }
  39168. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39169. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39170. return false;
  39171. }
  39172. else {
  39173. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39174. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39175. }
  39176. }
  39177. else {
  39178. defines.LIGHTMAP = false;
  39179. }
  39180. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39181. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39182. return false;
  39183. }
  39184. else {
  39185. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39186. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39187. }
  39188. }
  39189. else {
  39190. defines.SPECULAR = false;
  39191. }
  39192. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39193. // Bump texure can not be not blocking.
  39194. if (!this._bumpTexture.isReady()) {
  39195. return false;
  39196. }
  39197. else {
  39198. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39199. defines.PARALLAX = this._useParallax;
  39200. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39201. }
  39202. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39203. }
  39204. else {
  39205. defines.BUMP = false;
  39206. }
  39207. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39208. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  39209. return false;
  39210. }
  39211. else {
  39212. defines._needUVs = true;
  39213. defines.REFRACTION = true;
  39214. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  39215. }
  39216. }
  39217. else {
  39218. defines.REFRACTION = false;
  39219. }
  39220. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  39221. }
  39222. else {
  39223. defines.DIFFUSE = false;
  39224. defines.AMBIENT = false;
  39225. defines.OPACITY = false;
  39226. defines.REFLECTION = false;
  39227. defines.EMISSIVE = false;
  39228. defines.LIGHTMAP = false;
  39229. defines.BUMP = false;
  39230. defines.REFRACTION = false;
  39231. }
  39232. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  39233. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  39234. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  39235. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39236. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39237. }
  39238. if (defines._areImageProcessingDirty) {
  39239. if (!this._imageProcessingConfiguration.isReady()) {
  39240. return false;
  39241. }
  39242. this._imageProcessingConfiguration.prepareDefines(defines);
  39243. }
  39244. if (defines._areFresnelDirty) {
  39245. if (StandardMaterial.FresnelEnabled) {
  39246. // Fresnel
  39247. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  39248. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  39249. this._reflectionFresnelParameters) {
  39250. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  39251. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  39252. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  39253. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  39254. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  39255. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  39256. defines._needNormals = true;
  39257. defines.FRESNEL = true;
  39258. }
  39259. }
  39260. else {
  39261. defines.FRESNEL = false;
  39262. }
  39263. }
  39264. // Misc.
  39265. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  39266. // Attribs
  39267. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  39268. // Values that need to be evaluated on every frame
  39269. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  39270. // Get correct effect
  39271. if (defines.isDirty) {
  39272. defines.markAsProcessed();
  39273. scene.resetCachedMaterial();
  39274. // Fallbacks
  39275. var fallbacks = new BABYLON.EffectFallbacks();
  39276. if (defines.REFLECTION) {
  39277. fallbacks.addFallback(0, "REFLECTION");
  39278. }
  39279. if (defines.SPECULAR) {
  39280. fallbacks.addFallback(0, "SPECULAR");
  39281. }
  39282. if (defines.BUMP) {
  39283. fallbacks.addFallback(0, "BUMP");
  39284. }
  39285. if (defines.PARALLAX) {
  39286. fallbacks.addFallback(1, "PARALLAX");
  39287. }
  39288. if (defines.PARALLAXOCCLUSION) {
  39289. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  39290. }
  39291. if (defines.SPECULAROVERALPHA) {
  39292. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  39293. }
  39294. if (defines.FOG) {
  39295. fallbacks.addFallback(1, "FOG");
  39296. }
  39297. if (defines.POINTSIZE) {
  39298. fallbacks.addFallback(0, "POINTSIZE");
  39299. }
  39300. if (defines.LOGARITHMICDEPTH) {
  39301. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  39302. }
  39303. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  39304. if (defines.SPECULARTERM) {
  39305. fallbacks.addFallback(0, "SPECULARTERM");
  39306. }
  39307. if (defines.DIFFUSEFRESNEL) {
  39308. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  39309. }
  39310. if (defines.OPACITYFRESNEL) {
  39311. fallbacks.addFallback(2, "OPACITYFRESNEL");
  39312. }
  39313. if (defines.REFLECTIONFRESNEL) {
  39314. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  39315. }
  39316. if (defines.EMISSIVEFRESNEL) {
  39317. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  39318. }
  39319. if (defines.FRESNEL) {
  39320. fallbacks.addFallback(4, "FRESNEL");
  39321. }
  39322. //Attributes
  39323. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39324. if (defines.NORMAL) {
  39325. attribs.push(BABYLON.VertexBuffer.NormalKind);
  39326. }
  39327. if (defines.UV1) {
  39328. attribs.push(BABYLON.VertexBuffer.UVKind);
  39329. }
  39330. if (defines.UV2) {
  39331. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39332. }
  39333. if (defines.VERTEXCOLOR) {
  39334. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39335. }
  39336. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  39337. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  39338. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  39339. var shaderName = "default";
  39340. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  39341. "vFogInfos", "vFogColor", "pointSize",
  39342. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  39343. "mBones",
  39344. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  39345. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  39346. "vReflectionPosition", "vReflectionSize",
  39347. "logarithmicDepthConstant", "vTangentSpaceParams"
  39348. ];
  39349. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  39350. var uniformBuffers = ["Material", "Scene"];
  39351. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  39352. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  39353. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39354. uniformsNames: uniforms,
  39355. uniformBuffersNames: uniformBuffers,
  39356. samplers: samplers,
  39357. defines: defines,
  39358. maxSimultaneousLights: this._maxSimultaneousLights
  39359. });
  39360. if (this.customShaderNameResolve) {
  39361. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  39362. }
  39363. var join = defines.toString();
  39364. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  39365. attributes: attribs,
  39366. uniformsNames: uniforms,
  39367. uniformBuffersNames: uniformBuffers,
  39368. samplers: samplers,
  39369. defines: join,
  39370. fallbacks: fallbacks,
  39371. onCompiled: this.onCompiled,
  39372. onError: this.onError,
  39373. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  39374. }, engine), defines);
  39375. this.buildUniformLayout();
  39376. }
  39377. if (!subMesh.effect || !subMesh.effect.isReady()) {
  39378. return false;
  39379. }
  39380. defines._renderId = scene.getRenderId();
  39381. this._wasPreviouslyReady = true;
  39382. return true;
  39383. };
  39384. StandardMaterial.prototype.buildUniformLayout = function () {
  39385. // Order is important !
  39386. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  39387. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  39388. this._uniformBuffer.addUniform("opacityParts", 4);
  39389. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  39390. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  39391. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  39392. this._uniformBuffer.addUniform("refractionRightColor", 4);
  39393. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  39394. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  39395. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  39396. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  39397. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  39398. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  39399. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  39400. this._uniformBuffer.addUniform("vReflectionSize", 3);
  39401. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  39402. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  39403. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  39404. this._uniformBuffer.addUniform("vBumpInfos", 3);
  39405. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  39406. this._uniformBuffer.addUniform("ambientMatrix", 16);
  39407. this._uniformBuffer.addUniform("opacityMatrix", 16);
  39408. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  39409. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  39410. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  39411. this._uniformBuffer.addUniform("specularMatrix", 16);
  39412. this._uniformBuffer.addUniform("bumpMatrix", 16);
  39413. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  39414. this._uniformBuffer.addUniform("refractionMatrix", 16);
  39415. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  39416. this._uniformBuffer.addUniform("vSpecularColor", 4);
  39417. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  39418. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  39419. this._uniformBuffer.addUniform("pointSize", 1);
  39420. this._uniformBuffer.create();
  39421. };
  39422. StandardMaterial.prototype.unbind = function () {
  39423. if (this._activeEffect) {
  39424. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  39425. this._activeEffect.setTexture("reflection2DSampler", null);
  39426. }
  39427. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  39428. this._activeEffect.setTexture("refraction2DSampler", null);
  39429. }
  39430. }
  39431. _super.prototype.unbind.call(this);
  39432. };
  39433. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  39434. var scene = this.getScene();
  39435. var defines = subMesh._materialDefines;
  39436. if (!defines) {
  39437. return;
  39438. }
  39439. var effect = subMesh.effect;
  39440. if (!effect) {
  39441. return;
  39442. }
  39443. this._activeEffect = effect;
  39444. // Matrices
  39445. this.bindOnlyWorldMatrix(world);
  39446. // Normal Matrix
  39447. if (defines.OBJECTSPACE_NORMALMAP) {
  39448. world.toNormalMatrix(this._normalMatrix);
  39449. this.bindOnlyNormalMatrix(this._normalMatrix);
  39450. }
  39451. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  39452. // Bones
  39453. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  39454. if (mustRebind) {
  39455. this._uniformBuffer.bindToEffect(effect, "Material");
  39456. this.bindViewProjection(effect);
  39457. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  39458. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  39459. // Fresnel
  39460. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  39461. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  39462. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  39463. }
  39464. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  39465. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  39466. }
  39467. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  39468. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  39469. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  39470. }
  39471. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  39472. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  39473. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  39474. }
  39475. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  39476. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  39477. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  39478. }
  39479. }
  39480. // Textures
  39481. if (scene.texturesEnabled) {
  39482. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39483. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  39484. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  39485. }
  39486. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39487. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  39488. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  39489. }
  39490. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39491. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39492. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  39493. }
  39494. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39495. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  39496. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  39497. if (this._reflectionTexture.boundingBoxSize) {
  39498. var cubeTexture = this._reflectionTexture;
  39499. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  39500. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  39501. }
  39502. }
  39503. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39504. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39505. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  39506. }
  39507. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39508. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39509. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  39510. }
  39511. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39512. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  39513. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  39514. }
  39515. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39516. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  39517. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  39518. if (scene._mirroredCameraPosition) {
  39519. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  39520. }
  39521. else {
  39522. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  39523. }
  39524. }
  39525. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39526. var depth = 1.0;
  39527. if (!this._refractionTexture.isCube) {
  39528. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  39529. if (this._refractionTexture.depth) {
  39530. depth = this._refractionTexture.depth;
  39531. }
  39532. }
  39533. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  39534. }
  39535. }
  39536. // Point size
  39537. if (this.pointsCloud) {
  39538. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39539. }
  39540. if (defines.SPECULARTERM) {
  39541. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  39542. }
  39543. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  39544. // Diffuse
  39545. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  39546. }
  39547. // Textures
  39548. if (scene.texturesEnabled) {
  39549. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39550. effect.setTexture("diffuseSampler", this._diffuseTexture);
  39551. }
  39552. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39553. effect.setTexture("ambientSampler", this._ambientTexture);
  39554. }
  39555. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39556. effect.setTexture("opacitySampler", this._opacityTexture);
  39557. }
  39558. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39559. if (this._reflectionTexture.isCube) {
  39560. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  39561. }
  39562. else {
  39563. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  39564. }
  39565. }
  39566. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39567. effect.setTexture("emissiveSampler", this._emissiveTexture);
  39568. }
  39569. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39570. effect.setTexture("lightmapSampler", this._lightmapTexture);
  39571. }
  39572. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39573. effect.setTexture("specularSampler", this._specularTexture);
  39574. }
  39575. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39576. effect.setTexture("bumpSampler", this._bumpTexture);
  39577. }
  39578. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39579. var depth = 1.0;
  39580. if (this._refractionTexture.isCube) {
  39581. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  39582. }
  39583. else {
  39584. effect.setTexture("refraction2DSampler", this._refractionTexture);
  39585. }
  39586. }
  39587. }
  39588. // Clip plane
  39589. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  39590. // Colors
  39591. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  39592. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  39593. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39594. }
  39595. if (mustRebind || !this.isFrozen) {
  39596. // Lights
  39597. if (scene.lightsEnabled && !this._disableLighting) {
  39598. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  39599. }
  39600. // View
  39601. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  39602. this.bindView(effect);
  39603. }
  39604. // Fog
  39605. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  39606. // Morph targets
  39607. if (defines.NUM_MORPH_INFLUENCERS) {
  39608. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  39609. }
  39610. // Log. depth
  39611. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  39612. // image processing
  39613. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  39614. this._imageProcessingConfiguration.bind(this._activeEffect);
  39615. }
  39616. }
  39617. this._uniformBuffer.update();
  39618. this._afterBind(mesh, this._activeEffect);
  39619. };
  39620. StandardMaterial.prototype.getAnimatables = function () {
  39621. var results = [];
  39622. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  39623. results.push(this._diffuseTexture);
  39624. }
  39625. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39626. results.push(this._ambientTexture);
  39627. }
  39628. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39629. results.push(this._opacityTexture);
  39630. }
  39631. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39632. results.push(this._reflectionTexture);
  39633. }
  39634. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39635. results.push(this._emissiveTexture);
  39636. }
  39637. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  39638. results.push(this._specularTexture);
  39639. }
  39640. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39641. results.push(this._bumpTexture);
  39642. }
  39643. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39644. results.push(this._lightmapTexture);
  39645. }
  39646. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39647. results.push(this._refractionTexture);
  39648. }
  39649. return results;
  39650. };
  39651. StandardMaterial.prototype.getActiveTextures = function () {
  39652. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39653. if (this._diffuseTexture) {
  39654. activeTextures.push(this._diffuseTexture);
  39655. }
  39656. if (this._ambientTexture) {
  39657. activeTextures.push(this._ambientTexture);
  39658. }
  39659. if (this._opacityTexture) {
  39660. activeTextures.push(this._opacityTexture);
  39661. }
  39662. if (this._reflectionTexture) {
  39663. activeTextures.push(this._reflectionTexture);
  39664. }
  39665. if (this._emissiveTexture) {
  39666. activeTextures.push(this._emissiveTexture);
  39667. }
  39668. if (this._specularTexture) {
  39669. activeTextures.push(this._specularTexture);
  39670. }
  39671. if (this._bumpTexture) {
  39672. activeTextures.push(this._bumpTexture);
  39673. }
  39674. if (this._lightmapTexture) {
  39675. activeTextures.push(this._lightmapTexture);
  39676. }
  39677. if (this._refractionTexture) {
  39678. activeTextures.push(this._refractionTexture);
  39679. }
  39680. return activeTextures;
  39681. };
  39682. StandardMaterial.prototype.hasTexture = function (texture) {
  39683. if (_super.prototype.hasTexture.call(this, texture)) {
  39684. return true;
  39685. }
  39686. if (this._diffuseTexture === texture) {
  39687. return true;
  39688. }
  39689. if (this._ambientTexture === texture) {
  39690. return true;
  39691. }
  39692. if (this._opacityTexture === texture) {
  39693. return true;
  39694. }
  39695. if (this._reflectionTexture === texture) {
  39696. return true;
  39697. }
  39698. if (this._emissiveTexture === texture) {
  39699. return true;
  39700. }
  39701. if (this._specularTexture === texture) {
  39702. return true;
  39703. }
  39704. if (this._bumpTexture === texture) {
  39705. return true;
  39706. }
  39707. if (this._lightmapTexture === texture) {
  39708. return true;
  39709. }
  39710. if (this._refractionTexture === texture) {
  39711. return true;
  39712. }
  39713. return false;
  39714. };
  39715. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39716. if (forceDisposeTextures) {
  39717. if (this._diffuseTexture) {
  39718. this._diffuseTexture.dispose();
  39719. }
  39720. if (this._ambientTexture) {
  39721. this._ambientTexture.dispose();
  39722. }
  39723. if (this._opacityTexture) {
  39724. this._opacityTexture.dispose();
  39725. }
  39726. if (this._reflectionTexture) {
  39727. this._reflectionTexture.dispose();
  39728. }
  39729. if (this._emissiveTexture) {
  39730. this._emissiveTexture.dispose();
  39731. }
  39732. if (this._specularTexture) {
  39733. this._specularTexture.dispose();
  39734. }
  39735. if (this._bumpTexture) {
  39736. this._bumpTexture.dispose();
  39737. }
  39738. if (this._lightmapTexture) {
  39739. this._lightmapTexture.dispose();
  39740. }
  39741. if (this._refractionTexture) {
  39742. this._refractionTexture.dispose();
  39743. }
  39744. }
  39745. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39746. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39747. }
  39748. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39749. };
  39750. StandardMaterial.prototype.clone = function (name) {
  39751. var _this = this;
  39752. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  39753. result.name = name;
  39754. result.id = name;
  39755. return result;
  39756. };
  39757. StandardMaterial.prototype.serialize = function () {
  39758. return BABYLON.SerializationHelper.Serialize(this);
  39759. };
  39760. // Statics
  39761. StandardMaterial.Parse = function (source, scene, rootUrl) {
  39762. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  39763. };
  39764. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  39765. get: function () {
  39766. return StandardMaterial._DiffuseTextureEnabled;
  39767. },
  39768. set: function (value) {
  39769. if (StandardMaterial._DiffuseTextureEnabled === value) {
  39770. return;
  39771. }
  39772. StandardMaterial._DiffuseTextureEnabled = value;
  39773. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39774. },
  39775. enumerable: true,
  39776. configurable: true
  39777. });
  39778. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  39779. get: function () {
  39780. return StandardMaterial._AmbientTextureEnabled;
  39781. },
  39782. set: function (value) {
  39783. if (StandardMaterial._AmbientTextureEnabled === value) {
  39784. return;
  39785. }
  39786. StandardMaterial._AmbientTextureEnabled = value;
  39787. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39788. },
  39789. enumerable: true,
  39790. configurable: true
  39791. });
  39792. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  39793. get: function () {
  39794. return StandardMaterial._OpacityTextureEnabled;
  39795. },
  39796. set: function (value) {
  39797. if (StandardMaterial._OpacityTextureEnabled === value) {
  39798. return;
  39799. }
  39800. StandardMaterial._OpacityTextureEnabled = value;
  39801. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39802. },
  39803. enumerable: true,
  39804. configurable: true
  39805. });
  39806. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  39807. get: function () {
  39808. return StandardMaterial._ReflectionTextureEnabled;
  39809. },
  39810. set: function (value) {
  39811. if (StandardMaterial._ReflectionTextureEnabled === value) {
  39812. return;
  39813. }
  39814. StandardMaterial._ReflectionTextureEnabled = value;
  39815. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39816. },
  39817. enumerable: true,
  39818. configurable: true
  39819. });
  39820. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  39821. get: function () {
  39822. return StandardMaterial._EmissiveTextureEnabled;
  39823. },
  39824. set: function (value) {
  39825. if (StandardMaterial._EmissiveTextureEnabled === value) {
  39826. return;
  39827. }
  39828. StandardMaterial._EmissiveTextureEnabled = value;
  39829. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39830. },
  39831. enumerable: true,
  39832. configurable: true
  39833. });
  39834. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  39835. get: function () {
  39836. return StandardMaterial._SpecularTextureEnabled;
  39837. },
  39838. set: function (value) {
  39839. if (StandardMaterial._SpecularTextureEnabled === value) {
  39840. return;
  39841. }
  39842. StandardMaterial._SpecularTextureEnabled = value;
  39843. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39844. },
  39845. enumerable: true,
  39846. configurable: true
  39847. });
  39848. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  39849. get: function () {
  39850. return StandardMaterial._BumpTextureEnabled;
  39851. },
  39852. set: function (value) {
  39853. if (StandardMaterial._BumpTextureEnabled === value) {
  39854. return;
  39855. }
  39856. StandardMaterial._BumpTextureEnabled = value;
  39857. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39858. },
  39859. enumerable: true,
  39860. configurable: true
  39861. });
  39862. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  39863. get: function () {
  39864. return StandardMaterial._LightmapTextureEnabled;
  39865. },
  39866. set: function (value) {
  39867. if (StandardMaterial._LightmapTextureEnabled === value) {
  39868. return;
  39869. }
  39870. StandardMaterial._LightmapTextureEnabled = value;
  39871. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39872. },
  39873. enumerable: true,
  39874. configurable: true
  39875. });
  39876. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  39877. get: function () {
  39878. return StandardMaterial._RefractionTextureEnabled;
  39879. },
  39880. set: function (value) {
  39881. if (StandardMaterial._RefractionTextureEnabled === value) {
  39882. return;
  39883. }
  39884. StandardMaterial._RefractionTextureEnabled = value;
  39885. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39886. },
  39887. enumerable: true,
  39888. configurable: true
  39889. });
  39890. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  39891. get: function () {
  39892. return StandardMaterial._ColorGradingTextureEnabled;
  39893. },
  39894. set: function (value) {
  39895. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  39896. return;
  39897. }
  39898. StandardMaterial._ColorGradingTextureEnabled = value;
  39899. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39900. },
  39901. enumerable: true,
  39902. configurable: true
  39903. });
  39904. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  39905. get: function () {
  39906. return StandardMaterial._FresnelEnabled;
  39907. },
  39908. set: function (value) {
  39909. if (StandardMaterial._FresnelEnabled === value) {
  39910. return;
  39911. }
  39912. StandardMaterial._FresnelEnabled = value;
  39913. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  39914. },
  39915. enumerable: true,
  39916. configurable: true
  39917. });
  39918. // Flags used to enable or disable a type of texture for all Standard Materials
  39919. StandardMaterial._DiffuseTextureEnabled = true;
  39920. StandardMaterial._AmbientTextureEnabled = true;
  39921. StandardMaterial._OpacityTextureEnabled = true;
  39922. StandardMaterial._ReflectionTextureEnabled = true;
  39923. StandardMaterial._EmissiveTextureEnabled = true;
  39924. StandardMaterial._SpecularTextureEnabled = true;
  39925. StandardMaterial._BumpTextureEnabled = true;
  39926. StandardMaterial._LightmapTextureEnabled = true;
  39927. StandardMaterial._RefractionTextureEnabled = true;
  39928. StandardMaterial._ColorGradingTextureEnabled = true;
  39929. StandardMaterial._FresnelEnabled = true;
  39930. __decorate([
  39931. BABYLON.serializeAsTexture("diffuseTexture")
  39932. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  39933. __decorate([
  39934. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39935. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  39936. __decorate([
  39937. BABYLON.serializeAsTexture("ambientTexture")
  39938. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  39939. __decorate([
  39940. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39941. ], StandardMaterial.prototype, "ambientTexture", void 0);
  39942. __decorate([
  39943. BABYLON.serializeAsTexture("opacityTexture")
  39944. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  39945. __decorate([
  39946. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39947. ], StandardMaterial.prototype, "opacityTexture", void 0);
  39948. __decorate([
  39949. BABYLON.serializeAsTexture("reflectionTexture")
  39950. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  39951. __decorate([
  39952. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39953. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  39954. __decorate([
  39955. BABYLON.serializeAsTexture("emissiveTexture")
  39956. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  39957. __decorate([
  39958. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39959. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  39960. __decorate([
  39961. BABYLON.serializeAsTexture("specularTexture")
  39962. ], StandardMaterial.prototype, "_specularTexture", void 0);
  39963. __decorate([
  39964. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39965. ], StandardMaterial.prototype, "specularTexture", void 0);
  39966. __decorate([
  39967. BABYLON.serializeAsTexture("bumpTexture")
  39968. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  39969. __decorate([
  39970. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39971. ], StandardMaterial.prototype, "bumpTexture", void 0);
  39972. __decorate([
  39973. BABYLON.serializeAsTexture("lightmapTexture")
  39974. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  39975. __decorate([
  39976. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39977. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  39978. __decorate([
  39979. BABYLON.serializeAsTexture("refractionTexture")
  39980. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  39981. __decorate([
  39982. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39983. ], StandardMaterial.prototype, "refractionTexture", void 0);
  39984. __decorate([
  39985. BABYLON.serializeAsColor3("ambient")
  39986. ], StandardMaterial.prototype, "ambientColor", void 0);
  39987. __decorate([
  39988. BABYLON.serializeAsColor3("diffuse")
  39989. ], StandardMaterial.prototype, "diffuseColor", void 0);
  39990. __decorate([
  39991. BABYLON.serializeAsColor3("specular")
  39992. ], StandardMaterial.prototype, "specularColor", void 0);
  39993. __decorate([
  39994. BABYLON.serializeAsColor3("emissive")
  39995. ], StandardMaterial.prototype, "emissiveColor", void 0);
  39996. __decorate([
  39997. BABYLON.serialize()
  39998. ], StandardMaterial.prototype, "specularPower", void 0);
  39999. __decorate([
  40000. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40001. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40002. __decorate([
  40003. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40004. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40005. __decorate([
  40006. BABYLON.serialize("useEmissiveAsIllumination")
  40007. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40008. __decorate([
  40009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40010. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40011. __decorate([
  40012. BABYLON.serialize("linkEmissiveWithDiffuse")
  40013. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40014. __decorate([
  40015. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40016. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40017. __decorate([
  40018. BABYLON.serialize("useSpecularOverAlpha")
  40019. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40020. __decorate([
  40021. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40022. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40023. __decorate([
  40024. BABYLON.serialize("useReflectionOverAlpha")
  40025. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40026. __decorate([
  40027. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40028. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40029. __decorate([
  40030. BABYLON.serialize("disableLighting")
  40031. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40032. __decorate([
  40033. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40034. ], StandardMaterial.prototype, "disableLighting", void 0);
  40035. __decorate([
  40036. BABYLON.serialize("useObjectSpaceNormalMap")
  40037. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40038. __decorate([
  40039. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40040. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40041. __decorate([
  40042. BABYLON.serialize("useParallax")
  40043. ], StandardMaterial.prototype, "_useParallax", void 0);
  40044. __decorate([
  40045. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40046. ], StandardMaterial.prototype, "useParallax", void 0);
  40047. __decorate([
  40048. BABYLON.serialize("useParallaxOcclusion")
  40049. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40050. __decorate([
  40051. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40052. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40053. __decorate([
  40054. BABYLON.serialize()
  40055. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40056. __decorate([
  40057. BABYLON.serialize("roughness")
  40058. ], StandardMaterial.prototype, "_roughness", void 0);
  40059. __decorate([
  40060. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40061. ], StandardMaterial.prototype, "roughness", void 0);
  40062. __decorate([
  40063. BABYLON.serialize()
  40064. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40065. __decorate([
  40066. BABYLON.serialize()
  40067. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40068. __decorate([
  40069. BABYLON.serialize("useLightmapAsShadowmap")
  40070. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40071. __decorate([
  40072. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40073. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40074. __decorate([
  40075. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40076. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40077. __decorate([
  40078. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40079. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40080. __decorate([
  40081. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40082. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40083. __decorate([
  40084. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40085. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40086. __decorate([
  40087. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40088. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40089. __decorate([
  40090. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40091. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40092. __decorate([
  40093. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40094. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40095. __decorate([
  40096. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40097. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40098. __decorate([
  40099. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40100. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40101. __decorate([
  40102. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40103. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40104. __decorate([
  40105. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40106. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40107. __decorate([
  40108. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40109. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40110. __decorate([
  40111. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40112. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40113. __decorate([
  40114. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40115. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40116. __decorate([
  40117. BABYLON.serialize("maxSimultaneousLights")
  40118. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40119. __decorate([
  40120. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40121. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40122. __decorate([
  40123. BABYLON.serialize("invertNormalMapX")
  40124. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40125. __decorate([
  40126. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40127. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40128. __decorate([
  40129. BABYLON.serialize("invertNormalMapY")
  40130. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40131. __decorate([
  40132. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40133. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40134. __decorate([
  40135. BABYLON.serialize("twoSidedLighting")
  40136. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40137. __decorate([
  40138. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40139. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40140. __decorate([
  40141. BABYLON.serialize()
  40142. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40143. return StandardMaterial;
  40144. }(BABYLON.PushMaterial));
  40145. BABYLON.StandardMaterial = StandardMaterial;
  40146. })(BABYLON || (BABYLON = {}));
  40147. //# sourceMappingURL=babylon.standardMaterial.js.map
  40148. var BABYLON;
  40149. (function (BABYLON) {
  40150. /**
  40151. * Manages the defines for the PBR Material.
  40152. */
  40153. var PBRMaterialDefines = /** @class */ (function (_super) {
  40154. __extends(PBRMaterialDefines, _super);
  40155. /**
  40156. * Initializes the PBR Material defines.
  40157. */
  40158. function PBRMaterialDefines() {
  40159. var _this = _super.call(this) || this;
  40160. _this.PBR = true;
  40161. _this.MAINUV1 = false;
  40162. _this.MAINUV2 = false;
  40163. _this.UV1 = false;
  40164. _this.UV2 = false;
  40165. _this.ALBEDO = false;
  40166. _this.ALBEDODIRECTUV = 0;
  40167. _this.VERTEXCOLOR = false;
  40168. _this.AMBIENT = false;
  40169. _this.AMBIENTDIRECTUV = 0;
  40170. _this.AMBIENTINGRAYSCALE = false;
  40171. _this.OPACITY = false;
  40172. _this.VERTEXALPHA = false;
  40173. _this.OPACITYDIRECTUV = 0;
  40174. _this.OPACITYRGB = false;
  40175. _this.ALPHATEST = false;
  40176. _this.DEPTHPREPASS = false;
  40177. _this.ALPHABLEND = false;
  40178. _this.ALPHAFROMALBEDO = false;
  40179. _this.ALPHATESTVALUE = 0.5;
  40180. _this.SPECULAROVERALPHA = false;
  40181. _this.RADIANCEOVERALPHA = false;
  40182. _this.ALPHAFRESNEL = false;
  40183. _this.LINEARALPHAFRESNEL = false;
  40184. _this.PREMULTIPLYALPHA = false;
  40185. _this.EMISSIVE = false;
  40186. _this.EMISSIVEDIRECTUV = 0;
  40187. _this.REFLECTIVITY = false;
  40188. _this.REFLECTIVITYDIRECTUV = 0;
  40189. _this.SPECULARTERM = false;
  40190. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40191. _this.MICROSURFACEAUTOMATIC = false;
  40192. _this.LODBASEDMICROSFURACE = false;
  40193. _this.MICROSURFACEMAP = false;
  40194. _this.MICROSURFACEMAPDIRECTUV = 0;
  40195. _this.METALLICWORKFLOW = false;
  40196. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40197. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40198. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40199. _this.AOSTOREINMETALMAPRED = false;
  40200. _this.ENVIRONMENTBRDF = false;
  40201. _this.NORMAL = false;
  40202. _this.TANGENT = false;
  40203. _this.BUMP = false;
  40204. _this.BUMPDIRECTUV = 0;
  40205. _this.OBJECTSPACE_NORMALMAP = false;
  40206. _this.PARALLAX = false;
  40207. _this.PARALLAXOCCLUSION = false;
  40208. _this.NORMALXYSCALE = true;
  40209. _this.LIGHTMAP = false;
  40210. _this.LIGHTMAPDIRECTUV = 0;
  40211. _this.USELIGHTMAPASSHADOWMAP = false;
  40212. _this.REFLECTION = false;
  40213. _this.REFLECTIONMAP_3D = false;
  40214. _this.REFLECTIONMAP_SPHERICAL = false;
  40215. _this.REFLECTIONMAP_PLANAR = false;
  40216. _this.REFLECTIONMAP_CUBIC = false;
  40217. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40218. _this.REFLECTIONMAP_PROJECTION = false;
  40219. _this.REFLECTIONMAP_SKYBOX = false;
  40220. _this.REFLECTIONMAP_EXPLICIT = false;
  40221. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40222. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40223. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40224. _this.INVERTCUBICMAP = false;
  40225. _this.USESPHERICALFROMREFLECTIONMAP = false;
  40226. _this.USESPHERICALINVERTEX = false;
  40227. _this.REFLECTIONMAP_OPPOSITEZ = false;
  40228. _this.LODINREFLECTIONALPHA = false;
  40229. _this.GAMMAREFLECTION = false;
  40230. _this.RADIANCEOCCLUSION = false;
  40231. _this.HORIZONOCCLUSION = false;
  40232. _this.REFRACTION = false;
  40233. _this.REFRACTIONMAP_3D = false;
  40234. _this.REFRACTIONMAP_OPPOSITEZ = false;
  40235. _this.LODINREFRACTIONALPHA = false;
  40236. _this.GAMMAREFRACTION = false;
  40237. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  40238. _this.INSTANCES = false;
  40239. _this.NUM_BONE_INFLUENCERS = 0;
  40240. _this.BonesPerMesh = 0;
  40241. _this.NONUNIFORMSCALING = false;
  40242. _this.MORPHTARGETS = false;
  40243. _this.MORPHTARGETS_NORMAL = false;
  40244. _this.MORPHTARGETS_TANGENT = false;
  40245. _this.NUM_MORPH_INFLUENCERS = 0;
  40246. _this.IMAGEPROCESSING = false;
  40247. _this.VIGNETTE = false;
  40248. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  40249. _this.VIGNETTEBLENDMODEOPAQUE = false;
  40250. _this.TONEMAPPING = false;
  40251. _this.CONTRAST = false;
  40252. _this.COLORCURVES = false;
  40253. _this.COLORGRADING = false;
  40254. _this.COLORGRADING3D = false;
  40255. _this.SAMPLER3DGREENDEPTH = false;
  40256. _this.SAMPLER3DBGRMAP = false;
  40257. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  40258. _this.EXPOSURE = false;
  40259. _this.USEPHYSICALLIGHTFALLOFF = false;
  40260. _this.TWOSIDEDLIGHTING = false;
  40261. _this.SHADOWFLOAT = false;
  40262. _this.CLIPPLANE = false;
  40263. _this.POINTSIZE = false;
  40264. _this.FOG = false;
  40265. _this.LOGARITHMICDEPTH = false;
  40266. _this.FORCENORMALFORWARD = false;
  40267. _this.rebuild();
  40268. return _this;
  40269. }
  40270. /**
  40271. * Resets the PBR Material defines.
  40272. */
  40273. PBRMaterialDefines.prototype.reset = function () {
  40274. _super.prototype.reset.call(this);
  40275. this.ALPHATESTVALUE = 0.5;
  40276. this.PBR = true;
  40277. };
  40278. return PBRMaterialDefines;
  40279. }(BABYLON.MaterialDefines));
  40280. /**
  40281. * The Physically based material base class of BJS.
  40282. *
  40283. * This offers the main features of a standard PBR material.
  40284. * For more information, please refer to the documentation :
  40285. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  40286. */
  40287. var PBRBaseMaterial = /** @class */ (function (_super) {
  40288. __extends(PBRBaseMaterial, _super);
  40289. /**
  40290. * Instantiates a new PBRMaterial instance.
  40291. *
  40292. * @param name The material name
  40293. * @param scene The scene the material will be use in.
  40294. */
  40295. function PBRBaseMaterial(name, scene) {
  40296. var _this = _super.call(this, name, scene) || this;
  40297. /**
  40298. * Intensity of the direct lights e.g. the four lights available in your scene.
  40299. * This impacts both the direct diffuse and specular highlights.
  40300. */
  40301. _this._directIntensity = 1.0;
  40302. /**
  40303. * Intensity of the emissive part of the material.
  40304. * This helps controlling the emissive effect without modifying the emissive color.
  40305. */
  40306. _this._emissiveIntensity = 1.0;
  40307. /**
  40308. * Intensity of the environment e.g. how much the environment will light the object
  40309. * either through harmonics for rough material or through the refelction for shiny ones.
  40310. */
  40311. _this._environmentIntensity = 1.0;
  40312. /**
  40313. * This is a special control allowing the reduction of the specular highlights coming from the
  40314. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  40315. */
  40316. _this._specularIntensity = 1.0;
  40317. /**
  40318. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  40319. */
  40320. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  40321. /**
  40322. * Debug Control allowing disabling the bump map on this material.
  40323. */
  40324. _this._disableBumpMap = false;
  40325. /**
  40326. * AKA Occlusion Texture Intensity in other nomenclature.
  40327. */
  40328. _this._ambientTextureStrength = 1.0;
  40329. /**
  40330. * The color of a material in ambient lighting.
  40331. */
  40332. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  40333. /**
  40334. * AKA Diffuse Color in other nomenclature.
  40335. */
  40336. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  40337. /**
  40338. * AKA Specular Color in other nomenclature.
  40339. */
  40340. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  40341. /**
  40342. * The color applied when light is reflected from a material.
  40343. */
  40344. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  40345. /**
  40346. * The color applied when light is emitted from a material.
  40347. */
  40348. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  40349. /**
  40350. * AKA Glossiness in other nomenclature.
  40351. */
  40352. _this._microSurface = 0.9;
  40353. /**
  40354. * source material index of refraction (IOR)' / 'destination material IOR.
  40355. */
  40356. _this._indexOfRefraction = 0.66;
  40357. /**
  40358. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  40359. */
  40360. _this._invertRefractionY = false;
  40361. /**
  40362. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  40363. * Materials half opaque for instance using refraction could benefit from this control.
  40364. */
  40365. _this._linkRefractionWithTransparency = false;
  40366. /**
  40367. * Specifies that the material will use the light map as a show map.
  40368. */
  40369. _this._useLightmapAsShadowmap = false;
  40370. /**
  40371. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  40372. * makes the reflect vector face the model (under horizon).
  40373. */
  40374. _this._useHorizonOcclusion = true;
  40375. /**
  40376. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  40377. * too much the area relying on ambient texture to define their ambient occlusion.
  40378. */
  40379. _this._useRadianceOcclusion = true;
  40380. /**
  40381. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  40382. */
  40383. _this._useAlphaFromAlbedoTexture = false;
  40384. /**
  40385. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  40386. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  40387. */
  40388. _this._useSpecularOverAlpha = true;
  40389. /**
  40390. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  40391. */
  40392. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  40393. /**
  40394. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  40395. */
  40396. _this._useRoughnessFromMetallicTextureAlpha = true;
  40397. /**
  40398. * Specifies if the metallic texture contains the roughness information in its green channel.
  40399. */
  40400. _this._useRoughnessFromMetallicTextureGreen = false;
  40401. /**
  40402. * Specifies if the metallic texture contains the metallness information in its blue channel.
  40403. */
  40404. _this._useMetallnessFromMetallicTextureBlue = false;
  40405. /**
  40406. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  40407. */
  40408. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  40409. /**
  40410. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  40411. */
  40412. _this._useAmbientInGrayScale = false;
  40413. /**
  40414. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  40415. * The material will try to infer what glossiness each pixel should be.
  40416. */
  40417. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  40418. /**
  40419. * BJS is using an harcoded light falloff based on a manually sets up range.
  40420. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  40421. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  40422. */
  40423. _this._usePhysicalLightFalloff = true;
  40424. /**
  40425. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  40426. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  40427. */
  40428. _this._useRadianceOverAlpha = true;
  40429. /**
  40430. * Allows using an object space normal map (instead of tangent space).
  40431. */
  40432. _this._useObjectSpaceNormalMap = false;
  40433. /**
  40434. * Allows using the bump map in parallax mode.
  40435. */
  40436. _this._useParallax = false;
  40437. /**
  40438. * Allows using the bump map in parallax occlusion mode.
  40439. */
  40440. _this._useParallaxOcclusion = false;
  40441. /**
  40442. * Controls the scale bias of the parallax mode.
  40443. */
  40444. _this._parallaxScaleBias = 0.05;
  40445. /**
  40446. * If sets to true, disables all the lights affecting the material.
  40447. */
  40448. _this._disableLighting = false;
  40449. /**
  40450. * Number of Simultaneous lights allowed on the material.
  40451. */
  40452. _this._maxSimultaneousLights = 4;
  40453. /**
  40454. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  40455. */
  40456. _this._invertNormalMapX = false;
  40457. /**
  40458. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  40459. */
  40460. _this._invertNormalMapY = false;
  40461. /**
  40462. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  40463. */
  40464. _this._twoSidedLighting = false;
  40465. /**
  40466. * Defines the alpha limits in alpha test mode.
  40467. */
  40468. _this._alphaCutOff = 0.4;
  40469. /**
  40470. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  40471. */
  40472. _this._forceAlphaTest = false;
  40473. /**
  40474. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40475. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  40476. */
  40477. _this._useAlphaFresnel = false;
  40478. /**
  40479. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40480. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  40481. */
  40482. _this._useLinearAlphaFresnel = false;
  40483. /**
  40484. * The transparency mode of the material.
  40485. */
  40486. _this._transparencyMode = null;
  40487. /**
  40488. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  40489. * from cos thetav and roughness:
  40490. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  40491. */
  40492. _this._environmentBRDFTexture = null;
  40493. /**
  40494. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  40495. */
  40496. _this._forceIrradianceInFragment = false;
  40497. /**
  40498. * Force normal to face away from face.
  40499. */
  40500. _this._forceNormalForward = false;
  40501. /**
  40502. * Force metallic workflow.
  40503. */
  40504. _this._forceMetallicWorkflow = false;
  40505. /**
  40506. * Stores the available render targets.
  40507. */
  40508. _this._renderTargets = new BABYLON.SmartArray(16);
  40509. /**
  40510. * Sets the global ambient color for the material used in lighting calculations.
  40511. */
  40512. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  40513. // Setup the default processing configuration to the scene.
  40514. _this._attachImageProcessingConfiguration(null);
  40515. _this.getRenderTargetTextures = function () {
  40516. _this._renderTargets.reset();
  40517. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  40518. _this._renderTargets.push(_this._reflectionTexture);
  40519. }
  40520. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  40521. _this._renderTargets.push(_this._refractionTexture);
  40522. }
  40523. return _this._renderTargets;
  40524. };
  40525. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  40526. return _this;
  40527. }
  40528. /**
  40529. * Attaches a new image processing configuration to the PBR Material.
  40530. * @param configuration
  40531. */
  40532. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  40533. var _this = this;
  40534. if (configuration === this._imageProcessingConfiguration) {
  40535. return;
  40536. }
  40537. // Detaches observer.
  40538. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40539. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40540. }
  40541. // Pick the scene configuration if needed.
  40542. if (!configuration) {
  40543. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  40544. }
  40545. else {
  40546. this._imageProcessingConfiguration = configuration;
  40547. }
  40548. // Attaches observer.
  40549. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  40550. _this._markAllSubMeshesAsImageProcessingDirty();
  40551. });
  40552. };
  40553. /**
  40554. * Gets the name of the material class.
  40555. */
  40556. PBRBaseMaterial.prototype.getClassName = function () {
  40557. return "PBRBaseMaterial";
  40558. };
  40559. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  40560. /**
  40561. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40562. */
  40563. get: function () {
  40564. return this._useLogarithmicDepth;
  40565. },
  40566. /**
  40567. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40568. */
  40569. set: function (value) {
  40570. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  40571. },
  40572. enumerable: true,
  40573. configurable: true
  40574. });
  40575. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  40576. /**
  40577. * Gets the current transparency mode.
  40578. */
  40579. get: function () {
  40580. return this._transparencyMode;
  40581. },
  40582. /**
  40583. * Sets the transparency mode of the material.
  40584. */
  40585. set: function (value) {
  40586. if (this._transparencyMode === value) {
  40587. return;
  40588. }
  40589. this._transparencyMode = value;
  40590. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  40591. this._markAllSubMeshesAsTexturesAndMiscDirty();
  40592. },
  40593. enumerable: true,
  40594. configurable: true
  40595. });
  40596. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  40597. /**
  40598. * Returns true if alpha blending should be disabled.
  40599. */
  40600. get: function () {
  40601. return (this._linkRefractionWithTransparency ||
  40602. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  40603. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40604. },
  40605. enumerable: true,
  40606. configurable: true
  40607. });
  40608. /**
  40609. * Specifies whether or not this material should be rendered in alpha blend mode.
  40610. */
  40611. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  40612. if (this._disableAlphaBlending) {
  40613. return false;
  40614. }
  40615. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  40616. };
  40617. /**
  40618. * Specifies if the mesh will require alpha blending.
  40619. * @param mesh - BJS mesh.
  40620. */
  40621. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  40622. if (this._disableAlphaBlending) {
  40623. return false;
  40624. }
  40625. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  40626. };
  40627. /**
  40628. * Specifies whether or not this material should be rendered in alpha test mode.
  40629. */
  40630. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  40631. if (this._forceAlphaTest) {
  40632. return true;
  40633. }
  40634. if (this._linkRefractionWithTransparency) {
  40635. return false;
  40636. }
  40637. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40638. };
  40639. /**
  40640. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  40641. */
  40642. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  40643. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  40644. };
  40645. /**
  40646. * Gets the texture used for the alpha test.
  40647. */
  40648. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  40649. return this._albedoTexture;
  40650. };
  40651. /**
  40652. * Specifies that the submesh is ready to be used.
  40653. * @param mesh - BJS mesh.
  40654. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  40655. * @param useInstances - Specifies that instances should be used.
  40656. * @returns - boolean indicating that the submesh is ready or not.
  40657. */
  40658. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  40659. if (subMesh.effect && this.isFrozen) {
  40660. if (this._wasPreviouslyReady) {
  40661. return true;
  40662. }
  40663. }
  40664. if (!subMesh._materialDefines) {
  40665. subMesh._materialDefines = new PBRMaterialDefines();
  40666. }
  40667. var defines = subMesh._materialDefines;
  40668. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  40669. if (defines._renderId === this.getScene().getRenderId()) {
  40670. return true;
  40671. }
  40672. }
  40673. var scene = this.getScene();
  40674. var engine = scene.getEngine();
  40675. if (defines._areTexturesDirty) {
  40676. if (scene.texturesEnabled) {
  40677. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40678. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  40679. return false;
  40680. }
  40681. }
  40682. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40683. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  40684. return false;
  40685. }
  40686. }
  40687. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40688. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  40689. return false;
  40690. }
  40691. }
  40692. var reflectionTexture = this._getReflectionTexture();
  40693. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40694. if (!reflectionTexture.isReadyOrNotBlocking()) {
  40695. return false;
  40696. }
  40697. }
  40698. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40699. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  40700. return false;
  40701. }
  40702. }
  40703. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40704. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  40705. return false;
  40706. }
  40707. }
  40708. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40709. if (this._metallicTexture) {
  40710. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  40711. return false;
  40712. }
  40713. }
  40714. else if (this._reflectivityTexture) {
  40715. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  40716. return false;
  40717. }
  40718. }
  40719. if (this._microSurfaceTexture) {
  40720. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  40721. return false;
  40722. }
  40723. }
  40724. }
  40725. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40726. // Bump texture cannot be not blocking.
  40727. if (!this._bumpTexture.isReady()) {
  40728. return false;
  40729. }
  40730. }
  40731. var refractionTexture = this._getRefractionTexture();
  40732. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40733. if (!refractionTexture.isReadyOrNotBlocking()) {
  40734. return false;
  40735. }
  40736. }
  40737. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40738. // This is blocking.
  40739. if (!this._environmentBRDFTexture.isReady()) {
  40740. return false;
  40741. }
  40742. }
  40743. }
  40744. }
  40745. if (defines._areImageProcessingDirty) {
  40746. if (!this._imageProcessingConfiguration.isReady()) {
  40747. return false;
  40748. }
  40749. }
  40750. if (!engine.getCaps().standardDerivatives) {
  40751. var bufferMesh = null;
  40752. if (mesh.getClassName() === "InstancedMesh") {
  40753. bufferMesh = mesh.sourceMesh;
  40754. }
  40755. else if (mesh.getClassName() === "Mesh") {
  40756. bufferMesh = mesh;
  40757. }
  40758. if (bufferMesh && bufferMesh.geometry && bufferMesh.geometry.isReady() && !bufferMesh.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40759. bufferMesh.createNormals(true);
  40760. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  40761. }
  40762. }
  40763. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  40764. if (effect) {
  40765. scene.resetCachedMaterial();
  40766. subMesh.setEffect(effect, defines);
  40767. this.buildUniformLayout();
  40768. }
  40769. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40770. return false;
  40771. }
  40772. defines._renderId = scene.getRenderId();
  40773. this._wasPreviouslyReady = true;
  40774. return true;
  40775. };
  40776. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  40777. if (onCompiled === void 0) { onCompiled = null; }
  40778. if (onError === void 0) { onError = null; }
  40779. if (useInstances === void 0) { useInstances = null; }
  40780. if (useClipPlane === void 0) { useClipPlane = null; }
  40781. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  40782. if (!defines.isDirty) {
  40783. return null;
  40784. }
  40785. defines.markAsProcessed();
  40786. var scene = this.getScene();
  40787. var engine = scene.getEngine();
  40788. // Fallbacks
  40789. var fallbacks = new BABYLON.EffectFallbacks();
  40790. var fallbackRank = 0;
  40791. if (defines.USESPHERICALINVERTEX) {
  40792. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  40793. }
  40794. if (defines.FOG) {
  40795. fallbacks.addFallback(fallbackRank, "FOG");
  40796. }
  40797. if (defines.POINTSIZE) {
  40798. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  40799. }
  40800. if (defines.LOGARITHMICDEPTH) {
  40801. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  40802. }
  40803. if (defines.PARALLAX) {
  40804. fallbacks.addFallback(fallbackRank, "PARALLAX");
  40805. }
  40806. if (defines.PARALLAXOCCLUSION) {
  40807. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  40808. }
  40809. if (defines.ENVIRONMENTBRDF) {
  40810. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  40811. }
  40812. if (defines.TANGENT) {
  40813. fallbacks.addFallback(fallbackRank++, "TANGENT");
  40814. }
  40815. if (defines.BUMP) {
  40816. fallbacks.addFallback(fallbackRank++, "BUMP");
  40817. }
  40818. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  40819. if (defines.SPECULARTERM) {
  40820. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  40821. }
  40822. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  40823. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  40824. }
  40825. if (defines.LIGHTMAP) {
  40826. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  40827. }
  40828. if (defines.NORMAL) {
  40829. fallbacks.addFallback(fallbackRank++, "NORMAL");
  40830. }
  40831. if (defines.AMBIENT) {
  40832. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  40833. }
  40834. if (defines.EMISSIVE) {
  40835. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  40836. }
  40837. if (defines.VERTEXCOLOR) {
  40838. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  40839. }
  40840. if (defines.NUM_BONE_INFLUENCERS > 0) {
  40841. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  40842. }
  40843. if (defines.MORPHTARGETS) {
  40844. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  40845. }
  40846. //Attributes
  40847. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40848. if (defines.NORMAL) {
  40849. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40850. }
  40851. if (defines.TANGENT) {
  40852. attribs.push(BABYLON.VertexBuffer.TangentKind);
  40853. }
  40854. if (defines.UV1) {
  40855. attribs.push(BABYLON.VertexBuffer.UVKind);
  40856. }
  40857. if (defines.UV2) {
  40858. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40859. }
  40860. if (defines.VERTEXCOLOR) {
  40861. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40862. }
  40863. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40864. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40865. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40866. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  40867. "vFogInfos", "vFogColor", "pointSize",
  40868. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  40869. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40870. "mBones",
  40871. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  40872. "vLightingIntensity",
  40873. "logarithmicDepthConstant",
  40874. "vSphericalX", "vSphericalY", "vSphericalZ",
  40875. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  40876. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  40877. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  40878. "vTangentSpaceParams"
  40879. ];
  40880. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  40881. "bumpSampler", "lightmapSampler", "opacitySampler",
  40882. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  40883. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  40884. "microSurfaceSampler", "environmentBrdfSampler"];
  40885. var uniformBuffers = ["Material", "Scene"];
  40886. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40887. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40888. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40889. uniformsNames: uniforms,
  40890. uniformBuffersNames: uniformBuffers,
  40891. samplers: samplers,
  40892. defines: defines,
  40893. maxSimultaneousLights: this._maxSimultaneousLights
  40894. });
  40895. var join = defines.toString();
  40896. return engine.createEffect("pbr", {
  40897. attributes: attribs,
  40898. uniformsNames: uniforms,
  40899. uniformBuffersNames: uniformBuffers,
  40900. samplers: samplers,
  40901. defines: join,
  40902. fallbacks: fallbacks,
  40903. onCompiled: onCompiled,
  40904. onError: onError,
  40905. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40906. }, engine);
  40907. };
  40908. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  40909. if (useInstances === void 0) { useInstances = null; }
  40910. if (useClipPlane === void 0) { useClipPlane = null; }
  40911. var scene = this.getScene();
  40912. var engine = scene.getEngine();
  40913. // Lights
  40914. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  40915. defines._needNormals = true;
  40916. // Textures
  40917. if (defines._areTexturesDirty) {
  40918. defines._needUVs = false;
  40919. if (scene.texturesEnabled) {
  40920. if (scene.getEngine().getCaps().textureLOD) {
  40921. defines.LODBASEDMICROSFURACE = true;
  40922. }
  40923. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40924. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  40925. }
  40926. else {
  40927. defines.ALBEDO = false;
  40928. }
  40929. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40930. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  40931. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  40932. }
  40933. else {
  40934. defines.AMBIENT = false;
  40935. }
  40936. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40937. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  40938. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  40939. }
  40940. else {
  40941. defines.OPACITY = false;
  40942. }
  40943. var reflectionTexture = this._getReflectionTexture();
  40944. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40945. defines.REFLECTION = true;
  40946. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  40947. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  40948. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  40949. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  40950. defines.INVERTCUBICMAP = true;
  40951. }
  40952. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  40953. switch (reflectionTexture.coordinatesMode) {
  40954. case BABYLON.Texture.CUBIC_MODE:
  40955. case BABYLON.Texture.INVCUBIC_MODE:
  40956. defines.REFLECTIONMAP_CUBIC = true;
  40957. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  40958. break;
  40959. case BABYLON.Texture.EXPLICIT_MODE:
  40960. defines.REFLECTIONMAP_EXPLICIT = true;
  40961. break;
  40962. case BABYLON.Texture.PLANAR_MODE:
  40963. defines.REFLECTIONMAP_PLANAR = true;
  40964. break;
  40965. case BABYLON.Texture.PROJECTION_MODE:
  40966. defines.REFLECTIONMAP_PROJECTION = true;
  40967. break;
  40968. case BABYLON.Texture.SKYBOX_MODE:
  40969. defines.REFLECTIONMAP_SKYBOX = true;
  40970. break;
  40971. case BABYLON.Texture.SPHERICAL_MODE:
  40972. defines.REFLECTIONMAP_SPHERICAL = true;
  40973. break;
  40974. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  40975. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  40976. break;
  40977. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  40978. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  40979. break;
  40980. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  40981. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  40982. break;
  40983. }
  40984. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  40985. if (reflectionTexture.sphericalPolynomial) {
  40986. defines.USESPHERICALFROMREFLECTIONMAP = true;
  40987. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  40988. defines.USESPHERICALINVERTEX = false;
  40989. }
  40990. else {
  40991. defines.USESPHERICALINVERTEX = true;
  40992. }
  40993. }
  40994. }
  40995. }
  40996. else {
  40997. defines.REFLECTION = false;
  40998. defines.REFLECTIONMAP_3D = false;
  40999. defines.REFLECTIONMAP_SPHERICAL = false;
  41000. defines.REFLECTIONMAP_PLANAR = false;
  41001. defines.REFLECTIONMAP_CUBIC = false;
  41002. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41003. defines.REFLECTIONMAP_PROJECTION = false;
  41004. defines.REFLECTIONMAP_SKYBOX = false;
  41005. defines.REFLECTIONMAP_EXPLICIT = false;
  41006. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41007. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41008. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41009. defines.INVERTCUBICMAP = false;
  41010. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41011. defines.USESPHERICALINVERTEX = false;
  41012. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41013. defines.LODINREFLECTIONALPHA = false;
  41014. defines.GAMMAREFLECTION = false;
  41015. }
  41016. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41017. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41018. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41019. }
  41020. else {
  41021. defines.LIGHTMAP = false;
  41022. }
  41023. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41024. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41025. }
  41026. else {
  41027. defines.EMISSIVE = false;
  41028. }
  41029. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41030. if (this._metallicTexture) {
  41031. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41032. defines.METALLICWORKFLOW = true;
  41033. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41034. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41035. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41036. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41037. }
  41038. else if (this._reflectivityTexture) {
  41039. defines.METALLICWORKFLOW = false;
  41040. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41041. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41042. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41043. }
  41044. else {
  41045. defines.METALLICWORKFLOW = false;
  41046. defines.REFLECTIVITY = false;
  41047. }
  41048. if (this._microSurfaceTexture) {
  41049. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41050. }
  41051. else {
  41052. defines.MICROSURFACEMAP = false;
  41053. }
  41054. }
  41055. else {
  41056. defines.REFLECTIVITY = false;
  41057. defines.MICROSURFACEMAP = false;
  41058. }
  41059. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41060. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41061. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41062. defines.PARALLAX = true;
  41063. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41064. }
  41065. else {
  41066. defines.PARALLAX = false;
  41067. }
  41068. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41069. }
  41070. else {
  41071. defines.BUMP = false;
  41072. }
  41073. var refractionTexture = this._getRefractionTexture();
  41074. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41075. defines.REFRACTION = true;
  41076. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41077. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41078. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41079. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41080. if (this._linkRefractionWithTransparency) {
  41081. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41082. }
  41083. }
  41084. else {
  41085. defines.REFRACTION = false;
  41086. }
  41087. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41088. defines.ENVIRONMENTBRDF = true;
  41089. }
  41090. else {
  41091. defines.ENVIRONMENTBRDF = false;
  41092. }
  41093. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41094. defines.ALPHAFROMALBEDO = true;
  41095. }
  41096. else {
  41097. defines.ALPHAFROMALBEDO = false;
  41098. }
  41099. }
  41100. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41101. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41102. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41103. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  41104. defines.METALLICWORKFLOW = true;
  41105. }
  41106. else {
  41107. defines.METALLICWORKFLOW = false;
  41108. }
  41109. if (!this.backFaceCulling && this._twoSidedLighting) {
  41110. defines.TWOSIDEDLIGHTING = true;
  41111. }
  41112. else {
  41113. defines.TWOSIDEDLIGHTING = false;
  41114. }
  41115. defines.ALPHATESTVALUE = this._alphaCutOff;
  41116. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41117. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41118. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41119. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41120. }
  41121. if (defines._areImageProcessingDirty) {
  41122. this._imageProcessingConfiguration.prepareDefines(defines);
  41123. }
  41124. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41125. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41126. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41127. // Misc.
  41128. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41129. // Values that need to be evaluated on every frame
  41130. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41131. // Attribs
  41132. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41133. };
  41134. /**
  41135. * Force shader compilation
  41136. */
  41137. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41138. var _this = this;
  41139. var localOptions = __assign({ clipPlane: false }, options);
  41140. var defines = new PBRMaterialDefines();
  41141. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41142. if (effect.isReady()) {
  41143. if (onCompiled) {
  41144. onCompiled(this);
  41145. }
  41146. }
  41147. else {
  41148. effect.onCompileObservable.add(function () {
  41149. if (onCompiled) {
  41150. onCompiled(_this);
  41151. }
  41152. });
  41153. }
  41154. };
  41155. /**
  41156. * Initializes the uniform buffer layout for the shader.
  41157. */
  41158. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41159. // Order is important !
  41160. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41161. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41162. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41163. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41164. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41165. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41166. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41167. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41168. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41169. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41170. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41171. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41172. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41173. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41174. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41175. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41176. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41177. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41178. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41179. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41180. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41181. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41182. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41183. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41184. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41185. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41186. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41187. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41188. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41189. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41190. this._uniformBuffer.addUniform("pointSize", 1);
  41191. this._uniformBuffer.create();
  41192. };
  41193. /**
  41194. * Unbinds the textures.
  41195. */
  41196. PBRBaseMaterial.prototype.unbind = function () {
  41197. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41198. this._uniformBuffer.setTexture("reflectionSampler", null);
  41199. }
  41200. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41201. this._uniformBuffer.setTexture("refractionSampler", null);
  41202. }
  41203. _super.prototype.unbind.call(this);
  41204. };
  41205. /**
  41206. * Binds the submesh data.
  41207. * @param world - The world matrix.
  41208. * @param mesh - The BJS mesh.
  41209. * @param subMesh - A submesh of the BJS mesh.
  41210. */
  41211. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41212. var scene = this.getScene();
  41213. var defines = subMesh._materialDefines;
  41214. if (!defines) {
  41215. return;
  41216. }
  41217. var effect = subMesh.effect;
  41218. if (!effect) {
  41219. return;
  41220. }
  41221. this._activeEffect = effect;
  41222. // Matrices
  41223. this.bindOnlyWorldMatrix(world);
  41224. // Normal Matrix
  41225. if (defines.OBJECTSPACE_NORMALMAP) {
  41226. world.toNormalMatrix(this._normalMatrix);
  41227. this.bindOnlyNormalMatrix(this._normalMatrix);
  41228. }
  41229. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41230. // Bones
  41231. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  41232. var reflectionTexture = null;
  41233. if (mustRebind) {
  41234. this._uniformBuffer.bindToEffect(effect, "Material");
  41235. this.bindViewProjection(effect);
  41236. reflectionTexture = this._getReflectionTexture();
  41237. var refractionTexture = this._getRefractionTexture();
  41238. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41239. // Texture uniforms
  41240. if (scene.texturesEnabled) {
  41241. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41242. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  41243. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  41244. }
  41245. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41246. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  41247. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41248. }
  41249. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41250. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41251. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41252. }
  41253. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41254. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  41255. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  41256. if (reflectionTexture.boundingBoxSize) {
  41257. var cubeTexture = reflectionTexture;
  41258. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41259. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41260. }
  41261. var polynomials = reflectionTexture.sphericalPolynomial;
  41262. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  41263. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  41264. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  41265. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  41266. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  41267. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  41268. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  41269. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  41270. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  41271. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  41272. }
  41273. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  41274. }
  41275. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41276. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  41277. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  41278. }
  41279. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41280. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  41281. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  41282. }
  41283. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41284. if (this._metallicTexture) {
  41285. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  41286. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  41287. }
  41288. else if (this._reflectivityTexture) {
  41289. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  41290. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  41291. }
  41292. if (this._microSurfaceTexture) {
  41293. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  41294. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  41295. }
  41296. }
  41297. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41298. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  41299. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  41300. if (scene._mirroredCameraPosition) {
  41301. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  41302. }
  41303. else {
  41304. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  41305. }
  41306. }
  41307. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41308. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  41309. var depth = 1.0;
  41310. if (!refractionTexture.isCube) {
  41311. if (refractionTexture.depth) {
  41312. depth = refractionTexture.depth;
  41313. }
  41314. }
  41315. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  41316. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  41317. }
  41318. }
  41319. // Point size
  41320. if (this.pointsCloud) {
  41321. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  41322. }
  41323. // Colors
  41324. if (defines.METALLICWORKFLOW) {
  41325. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  41326. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  41327. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  41328. }
  41329. else {
  41330. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  41331. }
  41332. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  41333. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  41334. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  41335. // Misc
  41336. this._lightingInfos.x = this._directIntensity;
  41337. this._lightingInfos.y = this._emissiveIntensity;
  41338. this._lightingInfos.z = this._environmentIntensity;
  41339. this._lightingInfos.w = this._specularIntensity;
  41340. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  41341. }
  41342. // Textures
  41343. if (scene.texturesEnabled) {
  41344. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41345. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  41346. }
  41347. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41348. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  41349. }
  41350. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41351. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  41352. }
  41353. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41354. if (defines.LODBASEDMICROSFURACE) {
  41355. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  41356. }
  41357. else {
  41358. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  41359. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  41360. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  41361. }
  41362. }
  41363. if (defines.ENVIRONMENTBRDF) {
  41364. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  41365. }
  41366. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41367. if (defines.LODBASEDMICROSFURACE) {
  41368. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  41369. }
  41370. else {
  41371. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  41372. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  41373. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  41374. }
  41375. }
  41376. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41377. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  41378. }
  41379. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41380. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  41381. }
  41382. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41383. if (this._metallicTexture) {
  41384. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  41385. }
  41386. else if (this._reflectivityTexture) {
  41387. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  41388. }
  41389. if (this._microSurfaceTexture) {
  41390. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  41391. }
  41392. }
  41393. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41394. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  41395. }
  41396. }
  41397. // Clip plane
  41398. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  41399. // Colors
  41400. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  41401. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41402. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  41403. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  41404. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  41405. }
  41406. if (mustRebind || !this.isFrozen) {
  41407. // Lights
  41408. if (scene.lightsEnabled && !this._disableLighting) {
  41409. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  41410. }
  41411. // View
  41412. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  41413. this.bindView(effect);
  41414. }
  41415. // Fog
  41416. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  41417. // Morph targets
  41418. if (defines.NUM_MORPH_INFLUENCERS) {
  41419. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  41420. }
  41421. // image processing
  41422. this._imageProcessingConfiguration.bind(this._activeEffect);
  41423. // Log. depth
  41424. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  41425. }
  41426. this._uniformBuffer.update();
  41427. this._afterBind(mesh);
  41428. };
  41429. /**
  41430. * Returns the animatable textures.
  41431. * @returns - Array of animatable textures.
  41432. */
  41433. PBRBaseMaterial.prototype.getAnimatables = function () {
  41434. var results = [];
  41435. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  41436. results.push(this._albedoTexture);
  41437. }
  41438. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  41439. results.push(this._ambientTexture);
  41440. }
  41441. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  41442. results.push(this._opacityTexture);
  41443. }
  41444. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  41445. results.push(this._reflectionTexture);
  41446. }
  41447. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  41448. results.push(this._emissiveTexture);
  41449. }
  41450. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  41451. results.push(this._metallicTexture);
  41452. }
  41453. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  41454. results.push(this._reflectivityTexture);
  41455. }
  41456. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  41457. results.push(this._bumpTexture);
  41458. }
  41459. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  41460. results.push(this._lightmapTexture);
  41461. }
  41462. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  41463. results.push(this._refractionTexture);
  41464. }
  41465. return results;
  41466. };
  41467. /**
  41468. * Returns the texture used for reflections.
  41469. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  41470. */
  41471. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  41472. if (this._reflectionTexture) {
  41473. return this._reflectionTexture;
  41474. }
  41475. return this.getScene().environmentTexture;
  41476. };
  41477. /**
  41478. * Returns the texture used for refraction or null if none is used.
  41479. * @returns - Refection texture if present. If no refraction texture and refraction
  41480. * is linked with transparency, returns environment texture. Otherwise, returns null.
  41481. */
  41482. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  41483. if (this._refractionTexture) {
  41484. return this._refractionTexture;
  41485. }
  41486. if (this._linkRefractionWithTransparency) {
  41487. return this.getScene().environmentTexture;
  41488. }
  41489. return null;
  41490. };
  41491. /**
  41492. * Disposes the resources of the material.
  41493. * @param forceDisposeEffect - Forces the disposal of effects.
  41494. * @param forceDisposeTextures - Forces the disposal of all textures.
  41495. */
  41496. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41497. if (forceDisposeTextures) {
  41498. if (this._albedoTexture) {
  41499. this._albedoTexture.dispose();
  41500. }
  41501. if (this._ambientTexture) {
  41502. this._ambientTexture.dispose();
  41503. }
  41504. if (this._opacityTexture) {
  41505. this._opacityTexture.dispose();
  41506. }
  41507. if (this._reflectionTexture) {
  41508. this._reflectionTexture.dispose();
  41509. }
  41510. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  41511. this._environmentBRDFTexture.dispose();
  41512. }
  41513. if (this._emissiveTexture) {
  41514. this._emissiveTexture.dispose();
  41515. }
  41516. if (this._metallicTexture) {
  41517. this._metallicTexture.dispose();
  41518. }
  41519. if (this._reflectivityTexture) {
  41520. this._reflectivityTexture.dispose();
  41521. }
  41522. if (this._bumpTexture) {
  41523. this._bumpTexture.dispose();
  41524. }
  41525. if (this._lightmapTexture) {
  41526. this._lightmapTexture.dispose();
  41527. }
  41528. if (this._refractionTexture) {
  41529. this._refractionTexture.dispose();
  41530. }
  41531. }
  41532. this._renderTargets.dispose();
  41533. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41534. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41535. }
  41536. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41537. };
  41538. /**
  41539. * Stores the reflectivity values based on metallic roughness workflow.
  41540. */
  41541. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  41542. __decorate([
  41543. BABYLON.serializeAsImageProcessingConfiguration()
  41544. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  41545. __decorate([
  41546. BABYLON.serialize()
  41547. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  41548. __decorate([
  41549. BABYLON.serialize()
  41550. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  41551. return PBRBaseMaterial;
  41552. }(BABYLON.PushMaterial));
  41553. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  41554. })(BABYLON || (BABYLON = {}));
  41555. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  41556. var BABYLON;
  41557. (function (BABYLON) {
  41558. /**
  41559. * The Physically based simple base material of BJS.
  41560. *
  41561. * This enables better naming and convention enforcements on top of the pbrMaterial.
  41562. * It is used as the base class for both the specGloss and metalRough conventions.
  41563. */
  41564. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  41565. __extends(PBRBaseSimpleMaterial, _super);
  41566. /**
  41567. * Instantiates a new PBRMaterial instance.
  41568. *
  41569. * @param name The material name
  41570. * @param scene The scene the material will be use in.
  41571. */
  41572. function PBRBaseSimpleMaterial(name, scene) {
  41573. var _this = _super.call(this, name, scene) || this;
  41574. /**
  41575. * Number of Simultaneous lights allowed on the material.
  41576. */
  41577. _this.maxSimultaneousLights = 4;
  41578. /**
  41579. * If sets to true, disables all the lights affecting the material.
  41580. */
  41581. _this.disableLighting = false;
  41582. /**
  41583. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41584. */
  41585. _this.invertNormalMapX = false;
  41586. /**
  41587. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41588. */
  41589. _this.invertNormalMapY = false;
  41590. /**
  41591. * Emissivie color used to self-illuminate the model.
  41592. */
  41593. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41594. /**
  41595. * Occlusion Channel Strenght.
  41596. */
  41597. _this.occlusionStrength = 1.0;
  41598. _this.useLightmapAsShadowmap = false;
  41599. _this._useAlphaFromAlbedoTexture = true;
  41600. _this._useAmbientInGrayScale = true;
  41601. return _this;
  41602. }
  41603. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  41604. /**
  41605. * Gets the current double sided mode.
  41606. */
  41607. get: function () {
  41608. return this._twoSidedLighting;
  41609. },
  41610. /**
  41611. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41612. */
  41613. set: function (value) {
  41614. if (this._twoSidedLighting === value) {
  41615. return;
  41616. }
  41617. this._twoSidedLighting = value;
  41618. this.backFaceCulling = !value;
  41619. this._markAllSubMeshesAsTexturesDirty();
  41620. },
  41621. enumerable: true,
  41622. configurable: true
  41623. });
  41624. /**
  41625. * Return the active textures of the material.
  41626. */
  41627. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  41628. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41629. if (this.environmentTexture) {
  41630. activeTextures.push(this.environmentTexture);
  41631. }
  41632. if (this.normalTexture) {
  41633. activeTextures.push(this.normalTexture);
  41634. }
  41635. if (this.emissiveTexture) {
  41636. activeTextures.push(this.emissiveTexture);
  41637. }
  41638. if (this.occlusionTexture) {
  41639. activeTextures.push(this.occlusionTexture);
  41640. }
  41641. if (this.lightmapTexture) {
  41642. activeTextures.push(this.lightmapTexture);
  41643. }
  41644. return activeTextures;
  41645. };
  41646. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  41647. if (_super.prototype.hasTexture.call(this, texture)) {
  41648. return true;
  41649. }
  41650. if (this.lightmapTexture === texture) {
  41651. return true;
  41652. }
  41653. return false;
  41654. };
  41655. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  41656. return "PBRBaseSimpleMaterial";
  41657. };
  41658. __decorate([
  41659. BABYLON.serialize(),
  41660. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41661. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  41662. __decorate([
  41663. BABYLON.serialize(),
  41664. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41665. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  41666. __decorate([
  41667. BABYLON.serializeAsTexture(),
  41668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  41669. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  41670. __decorate([
  41671. BABYLON.serialize(),
  41672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41673. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  41674. __decorate([
  41675. BABYLON.serialize(),
  41676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41677. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  41678. __decorate([
  41679. BABYLON.serializeAsTexture(),
  41680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  41681. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  41682. __decorate([
  41683. BABYLON.serializeAsColor3("emissive"),
  41684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41685. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  41686. __decorate([
  41687. BABYLON.serializeAsTexture(),
  41688. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41689. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  41690. __decorate([
  41691. BABYLON.serialize(),
  41692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  41693. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  41694. __decorate([
  41695. BABYLON.serializeAsTexture(),
  41696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  41697. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  41698. __decorate([
  41699. BABYLON.serialize(),
  41700. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  41701. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  41702. __decorate([
  41703. BABYLON.serialize()
  41704. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  41705. __decorate([
  41706. BABYLON.serializeAsTexture(),
  41707. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41708. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  41709. __decorate([
  41710. BABYLON.serialize(),
  41711. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41712. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41713. return PBRBaseSimpleMaterial;
  41714. }(BABYLON.PBRBaseMaterial));
  41715. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  41716. })(BABYLON || (BABYLON = {}));
  41717. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  41718. var BABYLON;
  41719. (function (BABYLON) {
  41720. /**
  41721. * The Physically based material of BJS.
  41722. *
  41723. * This offers the main features of a standard PBR material.
  41724. * For more information, please refer to the documentation :
  41725. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41726. */
  41727. var PBRMaterial = /** @class */ (function (_super) {
  41728. __extends(PBRMaterial, _super);
  41729. /**
  41730. * Instantiates a new PBRMaterial instance.
  41731. *
  41732. * @param name The material name
  41733. * @param scene The scene the material will be use in.
  41734. */
  41735. function PBRMaterial(name, scene) {
  41736. var _this = _super.call(this, name, scene) || this;
  41737. /**
  41738. * Intensity of the direct lights e.g. the four lights available in your scene.
  41739. * This impacts both the direct diffuse and specular highlights.
  41740. */
  41741. _this.directIntensity = 1.0;
  41742. /**
  41743. * Intensity of the emissive part of the material.
  41744. * This helps controlling the emissive effect without modifying the emissive color.
  41745. */
  41746. _this.emissiveIntensity = 1.0;
  41747. /**
  41748. * Intensity of the environment e.g. how much the environment will light the object
  41749. * either through harmonics for rough material or through the refelction for shiny ones.
  41750. */
  41751. _this.environmentIntensity = 1.0;
  41752. /**
  41753. * This is a special control allowing the reduction of the specular highlights coming from the
  41754. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41755. */
  41756. _this.specularIntensity = 1.0;
  41757. /**
  41758. * Debug Control allowing disabling the bump map on this material.
  41759. */
  41760. _this.disableBumpMap = false;
  41761. /**
  41762. * AKA Occlusion Texture Intensity in other nomenclature.
  41763. */
  41764. _this.ambientTextureStrength = 1.0;
  41765. /**
  41766. * The color of a material in ambient lighting.
  41767. */
  41768. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41769. /**
  41770. * AKA Diffuse Color in other nomenclature.
  41771. */
  41772. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  41773. /**
  41774. * AKA Specular Color in other nomenclature.
  41775. */
  41776. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41777. /**
  41778. * The color reflected from the material.
  41779. */
  41780. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  41781. /**
  41782. * The color emitted from the material.
  41783. */
  41784. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41785. /**
  41786. * AKA Glossiness in other nomenclature.
  41787. */
  41788. _this.microSurface = 1.0;
  41789. /**
  41790. * source material index of refraction (IOR)' / 'destination material IOR.
  41791. */
  41792. _this.indexOfRefraction = 0.66;
  41793. /**
  41794. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41795. */
  41796. _this.invertRefractionY = false;
  41797. /**
  41798. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41799. * Materials half opaque for instance using refraction could benefit from this control.
  41800. */
  41801. _this.linkRefractionWithTransparency = false;
  41802. _this.useLightmapAsShadowmap = false;
  41803. /**
  41804. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41805. */
  41806. _this.useAlphaFromAlbedoTexture = false;
  41807. /**
  41808. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41809. */
  41810. _this.forceAlphaTest = false;
  41811. /**
  41812. * Defines the alpha limits in alpha test mode.
  41813. */
  41814. _this.alphaCutOff = 0.4;
  41815. /**
  41816. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41817. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41818. */
  41819. _this.useSpecularOverAlpha = true;
  41820. /**
  41821. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41822. */
  41823. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  41824. /**
  41825. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41826. */
  41827. _this.useRoughnessFromMetallicTextureAlpha = true;
  41828. /**
  41829. * Specifies if the metallic texture contains the roughness information in its green channel.
  41830. */
  41831. _this.useRoughnessFromMetallicTextureGreen = false;
  41832. /**
  41833. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41834. */
  41835. _this.useMetallnessFromMetallicTextureBlue = false;
  41836. /**
  41837. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41838. */
  41839. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  41840. /**
  41841. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41842. */
  41843. _this.useAmbientInGrayScale = false;
  41844. /**
  41845. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41846. * The material will try to infer what glossiness each pixel should be.
  41847. */
  41848. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  41849. /**
  41850. * BJS is using an harcoded light falloff based on a manually sets up range.
  41851. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41852. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41853. */
  41854. _this.usePhysicalLightFalloff = true;
  41855. /**
  41856. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41857. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41858. */
  41859. _this.useRadianceOverAlpha = true;
  41860. /**
  41861. * Allows using an object space normal map (instead of tangent space).
  41862. */
  41863. _this.useObjectSpaceNormalMap = false;
  41864. /**
  41865. * Allows using the bump map in parallax mode.
  41866. */
  41867. _this.useParallax = false;
  41868. /**
  41869. * Allows using the bump map in parallax occlusion mode.
  41870. */
  41871. _this.useParallaxOcclusion = false;
  41872. /**
  41873. * Controls the scale bias of the parallax mode.
  41874. */
  41875. _this.parallaxScaleBias = 0.05;
  41876. /**
  41877. * If sets to true, disables all the lights affecting the material.
  41878. */
  41879. _this.disableLighting = false;
  41880. /**
  41881. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41882. */
  41883. _this.forceIrradianceInFragment = false;
  41884. /**
  41885. * Number of Simultaneous lights allowed on the material.
  41886. */
  41887. _this.maxSimultaneousLights = 4;
  41888. /**
  41889. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41890. */
  41891. _this.invertNormalMapX = false;
  41892. /**
  41893. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41894. */
  41895. _this.invertNormalMapY = false;
  41896. /**
  41897. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41898. */
  41899. _this.twoSidedLighting = false;
  41900. /**
  41901. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41902. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41903. */
  41904. _this.useAlphaFresnel = false;
  41905. /**
  41906. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41907. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41908. */
  41909. _this.useLinearAlphaFresnel = false;
  41910. /**
  41911. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41912. * And/Or occlude the blended part.
  41913. */
  41914. _this.environmentBRDFTexture = null;
  41915. /**
  41916. * Force normal to face away from face.
  41917. */
  41918. _this.forceNormalForward = false;
  41919. /**
  41920. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41921. * makes the reflect vector face the model (under horizon).
  41922. */
  41923. _this.useHorizonOcclusion = true;
  41924. /**
  41925. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41926. * too much the area relying on ambient texture to define their ambient occlusion.
  41927. */
  41928. _this.useRadianceOcclusion = true;
  41929. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41930. return _this;
  41931. }
  41932. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  41933. /**
  41934. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  41935. */
  41936. get: function () {
  41937. return this._PBRMATERIAL_OPAQUE;
  41938. },
  41939. enumerable: true,
  41940. configurable: true
  41941. });
  41942. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  41943. /**
  41944. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  41945. */
  41946. get: function () {
  41947. return this._PBRMATERIAL_ALPHATEST;
  41948. },
  41949. enumerable: true,
  41950. configurable: true
  41951. });
  41952. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  41953. /**
  41954. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41955. */
  41956. get: function () {
  41957. return this._PBRMATERIAL_ALPHABLEND;
  41958. },
  41959. enumerable: true,
  41960. configurable: true
  41961. });
  41962. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  41963. /**
  41964. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41965. * They are also discarded below the alpha cutoff threshold to improve performances.
  41966. */
  41967. get: function () {
  41968. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  41969. },
  41970. enumerable: true,
  41971. configurable: true
  41972. });
  41973. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  41974. /**
  41975. * Gets the image processing configuration used either in this material.
  41976. */
  41977. get: function () {
  41978. return this._imageProcessingConfiguration;
  41979. },
  41980. /**
  41981. * Sets the Default image processing configuration used either in the this material.
  41982. *
  41983. * If sets to null, the scene one is in use.
  41984. */
  41985. set: function (value) {
  41986. this._attachImageProcessingConfiguration(value);
  41987. // Ensure the effect will be rebuilt.
  41988. this._markAllSubMeshesAsTexturesDirty();
  41989. },
  41990. enumerable: true,
  41991. configurable: true
  41992. });
  41993. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  41994. /**
  41995. * Gets wether the color curves effect is enabled.
  41996. */
  41997. get: function () {
  41998. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41999. },
  42000. /**
  42001. * Sets wether the color curves effect is enabled.
  42002. */
  42003. set: function (value) {
  42004. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42005. },
  42006. enumerable: true,
  42007. configurable: true
  42008. });
  42009. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42010. /**
  42011. * Gets wether the color grading effect is enabled.
  42012. */
  42013. get: function () {
  42014. return this.imageProcessingConfiguration.colorGradingEnabled;
  42015. },
  42016. /**
  42017. * Gets wether the color grading effect is enabled.
  42018. */
  42019. set: function (value) {
  42020. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42021. },
  42022. enumerable: true,
  42023. configurable: true
  42024. });
  42025. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42026. /**
  42027. * Gets wether tonemapping is enabled or not.
  42028. */
  42029. get: function () {
  42030. return this._imageProcessingConfiguration.toneMappingEnabled;
  42031. },
  42032. /**
  42033. * Sets wether tonemapping is enabled or not
  42034. */
  42035. set: function (value) {
  42036. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42037. },
  42038. enumerable: true,
  42039. configurable: true
  42040. });
  42041. ;
  42042. ;
  42043. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42044. /**
  42045. * The camera exposure used on this material.
  42046. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42047. * This corresponds to a photographic exposure.
  42048. */
  42049. get: function () {
  42050. return this._imageProcessingConfiguration.exposure;
  42051. },
  42052. /**
  42053. * The camera exposure used on this material.
  42054. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42055. * This corresponds to a photographic exposure.
  42056. */
  42057. set: function (value) {
  42058. this._imageProcessingConfiguration.exposure = value;
  42059. },
  42060. enumerable: true,
  42061. configurable: true
  42062. });
  42063. ;
  42064. ;
  42065. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42066. /**
  42067. * Gets The camera contrast used on this material.
  42068. */
  42069. get: function () {
  42070. return this._imageProcessingConfiguration.contrast;
  42071. },
  42072. /**
  42073. * Sets The camera contrast used on this material.
  42074. */
  42075. set: function (value) {
  42076. this._imageProcessingConfiguration.contrast = value;
  42077. },
  42078. enumerable: true,
  42079. configurable: true
  42080. });
  42081. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42082. /**
  42083. * Gets the Color Grading 2D Lookup Texture.
  42084. */
  42085. get: function () {
  42086. return this._imageProcessingConfiguration.colorGradingTexture;
  42087. },
  42088. /**
  42089. * Sets the Color Grading 2D Lookup Texture.
  42090. */
  42091. set: function (value) {
  42092. this._imageProcessingConfiguration.colorGradingTexture = value;
  42093. },
  42094. enumerable: true,
  42095. configurable: true
  42096. });
  42097. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42098. /**
  42099. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42100. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42101. * 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;
  42102. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42103. */
  42104. get: function () {
  42105. return this._imageProcessingConfiguration.colorCurves;
  42106. },
  42107. /**
  42108. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42109. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42110. * 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;
  42111. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42112. */
  42113. set: function (value) {
  42114. this._imageProcessingConfiguration.colorCurves = value;
  42115. },
  42116. enumerable: true,
  42117. configurable: true
  42118. });
  42119. /**
  42120. * Returns the name of this material class.
  42121. */
  42122. PBRMaterial.prototype.getClassName = function () {
  42123. return "PBRMaterial";
  42124. };
  42125. /**
  42126. * Returns an array of the actively used textures.
  42127. * @returns - Array of BaseTextures
  42128. */
  42129. PBRMaterial.prototype.getActiveTextures = function () {
  42130. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42131. if (this._albedoTexture) {
  42132. activeTextures.push(this._albedoTexture);
  42133. }
  42134. if (this._ambientTexture) {
  42135. activeTextures.push(this._ambientTexture);
  42136. }
  42137. if (this._opacityTexture) {
  42138. activeTextures.push(this._opacityTexture);
  42139. }
  42140. if (this._reflectionTexture) {
  42141. activeTextures.push(this._reflectionTexture);
  42142. }
  42143. if (this._emissiveTexture) {
  42144. activeTextures.push(this._emissiveTexture);
  42145. }
  42146. if (this._reflectivityTexture) {
  42147. activeTextures.push(this._reflectivityTexture);
  42148. }
  42149. if (this._metallicTexture) {
  42150. activeTextures.push(this._metallicTexture);
  42151. }
  42152. if (this._microSurfaceTexture) {
  42153. activeTextures.push(this._microSurfaceTexture);
  42154. }
  42155. if (this._bumpTexture) {
  42156. activeTextures.push(this._bumpTexture);
  42157. }
  42158. if (this._lightmapTexture) {
  42159. activeTextures.push(this._lightmapTexture);
  42160. }
  42161. if (this._refractionTexture) {
  42162. activeTextures.push(this._refractionTexture);
  42163. }
  42164. return activeTextures;
  42165. };
  42166. /**
  42167. * Checks to see if a texture is used in the material.
  42168. * @param texture - Base texture to use.
  42169. * @returns - Boolean specifying if a texture is used in the material.
  42170. */
  42171. PBRMaterial.prototype.hasTexture = function (texture) {
  42172. if (_super.prototype.hasTexture.call(this, texture)) {
  42173. return true;
  42174. }
  42175. if (this._albedoTexture === texture) {
  42176. return true;
  42177. }
  42178. if (this._ambientTexture === texture) {
  42179. return true;
  42180. }
  42181. if (this._opacityTexture === texture) {
  42182. return true;
  42183. }
  42184. if (this._reflectionTexture === texture) {
  42185. return true;
  42186. }
  42187. if (this._reflectivityTexture === texture) {
  42188. return true;
  42189. }
  42190. if (this._metallicTexture === texture) {
  42191. return true;
  42192. }
  42193. if (this._microSurfaceTexture === texture) {
  42194. return true;
  42195. }
  42196. if (this._bumpTexture === texture) {
  42197. return true;
  42198. }
  42199. if (this._lightmapTexture === texture) {
  42200. return true;
  42201. }
  42202. if (this._refractionTexture === texture) {
  42203. return true;
  42204. }
  42205. return false;
  42206. };
  42207. /**
  42208. * Makes a duplicate of the current material.
  42209. * @param name - name to use for the new material.
  42210. */
  42211. PBRMaterial.prototype.clone = function (name) {
  42212. var _this = this;
  42213. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  42214. clone.id = name;
  42215. clone.name = name;
  42216. return clone;
  42217. };
  42218. /**
  42219. * Serializes this PBR Material.
  42220. * @returns - An object with the serialized material.
  42221. */
  42222. PBRMaterial.prototype.serialize = function () {
  42223. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42224. serializationObject.customType = "BABYLON.PBRMaterial";
  42225. return serializationObject;
  42226. };
  42227. // Statics
  42228. /**
  42229. * Parses a PBR Material from a serialized object.
  42230. * @param source - Serialized object.
  42231. * @param scene - BJS scene instance.
  42232. * @param rootUrl - url for the scene object
  42233. * @returns - PBRMaterial
  42234. */
  42235. PBRMaterial.Parse = function (source, scene, rootUrl) {
  42236. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  42237. };
  42238. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  42239. /**
  42240. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42241. */
  42242. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  42243. /**
  42244. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42245. */
  42246. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  42247. /**
  42248. * 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.
  42249. * They are also discarded below the alpha cutoff threshold to improve performances.
  42250. */
  42251. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  42252. __decorate([
  42253. BABYLON.serialize(),
  42254. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42255. ], PBRMaterial.prototype, "directIntensity", void 0);
  42256. __decorate([
  42257. BABYLON.serialize(),
  42258. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42259. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  42260. __decorate([
  42261. BABYLON.serialize(),
  42262. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42263. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  42264. __decorate([
  42265. BABYLON.serialize(),
  42266. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42267. ], PBRMaterial.prototype, "specularIntensity", void 0);
  42268. __decorate([
  42269. BABYLON.serialize(),
  42270. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42271. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  42272. __decorate([
  42273. BABYLON.serializeAsTexture(),
  42274. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42275. ], PBRMaterial.prototype, "albedoTexture", void 0);
  42276. __decorate([
  42277. BABYLON.serializeAsTexture(),
  42278. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42279. ], PBRMaterial.prototype, "ambientTexture", void 0);
  42280. __decorate([
  42281. BABYLON.serialize(),
  42282. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42283. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  42284. __decorate([
  42285. BABYLON.serializeAsTexture(),
  42286. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42287. ], PBRMaterial.prototype, "opacityTexture", void 0);
  42288. __decorate([
  42289. BABYLON.serializeAsTexture(),
  42290. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42291. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  42292. __decorate([
  42293. BABYLON.serializeAsTexture(),
  42294. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42295. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  42296. __decorate([
  42297. BABYLON.serializeAsTexture(),
  42298. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42299. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  42300. __decorate([
  42301. BABYLON.serializeAsTexture(),
  42302. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42303. ], PBRMaterial.prototype, "metallicTexture", void 0);
  42304. __decorate([
  42305. BABYLON.serialize(),
  42306. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42307. ], PBRMaterial.prototype, "metallic", void 0);
  42308. __decorate([
  42309. BABYLON.serialize(),
  42310. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42311. ], PBRMaterial.prototype, "roughness", void 0);
  42312. __decorate([
  42313. BABYLON.serializeAsTexture(),
  42314. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42315. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  42316. __decorate([
  42317. BABYLON.serializeAsTexture(),
  42318. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42319. ], PBRMaterial.prototype, "bumpTexture", void 0);
  42320. __decorate([
  42321. BABYLON.serializeAsTexture(),
  42322. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42323. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  42324. __decorate([
  42325. BABYLON.serializeAsTexture(),
  42326. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42327. ], PBRMaterial.prototype, "refractionTexture", void 0);
  42328. __decorate([
  42329. BABYLON.serializeAsColor3("ambient"),
  42330. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42331. ], PBRMaterial.prototype, "ambientColor", void 0);
  42332. __decorate([
  42333. BABYLON.serializeAsColor3("albedo"),
  42334. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42335. ], PBRMaterial.prototype, "albedoColor", void 0);
  42336. __decorate([
  42337. BABYLON.serializeAsColor3("reflectivity"),
  42338. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42339. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  42340. __decorate([
  42341. BABYLON.serializeAsColor3("reflection"),
  42342. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42343. ], PBRMaterial.prototype, "reflectionColor", void 0);
  42344. __decorate([
  42345. BABYLON.serializeAsColor3("emissive"),
  42346. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42347. ], PBRMaterial.prototype, "emissiveColor", void 0);
  42348. __decorate([
  42349. BABYLON.serialize(),
  42350. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42351. ], PBRMaterial.prototype, "microSurface", void 0);
  42352. __decorate([
  42353. BABYLON.serialize(),
  42354. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42355. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  42356. __decorate([
  42357. BABYLON.serialize(),
  42358. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42359. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  42360. __decorate([
  42361. BABYLON.serialize(),
  42362. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42363. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  42364. __decorate([
  42365. BABYLON.serialize(),
  42366. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42367. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42368. __decorate([
  42369. BABYLON.serialize(),
  42370. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42371. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  42372. __decorate([
  42373. BABYLON.serialize(),
  42374. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42375. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  42376. __decorate([
  42377. BABYLON.serialize(),
  42378. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42379. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  42380. __decorate([
  42381. BABYLON.serialize(),
  42382. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42383. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  42384. __decorate([
  42385. BABYLON.serialize(),
  42386. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42387. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  42388. __decorate([
  42389. BABYLON.serialize(),
  42390. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42391. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  42392. __decorate([
  42393. BABYLON.serialize(),
  42394. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42395. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  42396. __decorate([
  42397. BABYLON.serialize(),
  42398. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42399. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  42400. __decorate([
  42401. BABYLON.serialize(),
  42402. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42403. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  42404. __decorate([
  42405. BABYLON.serialize(),
  42406. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42407. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  42408. __decorate([
  42409. BABYLON.serialize(),
  42410. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42411. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  42412. __decorate([
  42413. BABYLON.serialize(),
  42414. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42415. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  42416. __decorate([
  42417. BABYLON.serialize(),
  42418. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42419. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  42420. __decorate([
  42421. BABYLON.serialize(),
  42422. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42423. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42424. __decorate([
  42425. BABYLON.serialize(),
  42426. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42427. ], PBRMaterial.prototype, "useParallax", void 0);
  42428. __decorate([
  42429. BABYLON.serialize(),
  42430. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42431. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  42432. __decorate([
  42433. BABYLON.serialize(),
  42434. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42435. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  42436. __decorate([
  42437. BABYLON.serialize(),
  42438. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42439. ], PBRMaterial.prototype, "disableLighting", void 0);
  42440. __decorate([
  42441. BABYLON.serialize(),
  42442. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42443. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  42444. __decorate([
  42445. BABYLON.serialize(),
  42446. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42447. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  42448. __decorate([
  42449. BABYLON.serialize(),
  42450. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42451. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  42452. __decorate([
  42453. BABYLON.serialize(),
  42454. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42455. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  42456. __decorate([
  42457. BABYLON.serialize(),
  42458. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42459. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  42460. __decorate([
  42461. BABYLON.serialize(),
  42462. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42463. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  42464. __decorate([
  42465. BABYLON.serialize(),
  42466. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42467. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  42468. __decorate([
  42469. BABYLON.serializeAsTexture(),
  42470. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42471. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  42472. __decorate([
  42473. BABYLON.serialize(),
  42474. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42475. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  42476. __decorate([
  42477. BABYLON.serialize(),
  42478. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42479. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  42480. __decorate([
  42481. BABYLON.serialize(),
  42482. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42483. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  42484. return PBRMaterial;
  42485. }(BABYLON.PBRBaseMaterial));
  42486. BABYLON.PBRMaterial = PBRMaterial;
  42487. })(BABYLON || (BABYLON = {}));
  42488. //# sourceMappingURL=babylon.pbrMaterial.js.map
  42489. var BABYLON;
  42490. (function (BABYLON) {
  42491. /**
  42492. * The PBR material of BJS following the metal roughness convention.
  42493. *
  42494. * This fits to the PBR convention in the GLTF definition:
  42495. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  42496. */
  42497. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  42498. __extends(PBRMetallicRoughnessMaterial, _super);
  42499. /**
  42500. * Instantiates a new PBRMetalRoughnessMaterial instance.
  42501. *
  42502. * @param name The material name
  42503. * @param scene The scene the material will be use in.
  42504. */
  42505. function PBRMetallicRoughnessMaterial(name, scene) {
  42506. var _this = _super.call(this, name, scene) || this;
  42507. _this._useRoughnessFromMetallicTextureAlpha = false;
  42508. _this._useRoughnessFromMetallicTextureGreen = true;
  42509. _this._useMetallnessFromMetallicTextureBlue = true;
  42510. _this._forceMetallicWorkflow = true;
  42511. return _this;
  42512. }
  42513. /**
  42514. * Return the currrent class name of the material.
  42515. */
  42516. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  42517. return "PBRMetallicRoughnessMaterial";
  42518. };
  42519. /**
  42520. * Return the active textures of the material.
  42521. */
  42522. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  42523. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42524. if (this.baseTexture) {
  42525. activeTextures.push(this.baseTexture);
  42526. }
  42527. if (this.metallicRoughnessTexture) {
  42528. activeTextures.push(this.metallicRoughnessTexture);
  42529. }
  42530. return activeTextures;
  42531. };
  42532. /**
  42533. * Checks to see if a texture is used in the material.
  42534. * @param texture - Base texture to use.
  42535. * @returns - Boolean specifying if a texture is used in the material.
  42536. */
  42537. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  42538. if (_super.prototype.hasTexture.call(this, texture)) {
  42539. return true;
  42540. }
  42541. if (this.baseTexture === texture) {
  42542. return true;
  42543. }
  42544. if (this.metallicRoughnessTexture === texture) {
  42545. return true;
  42546. }
  42547. return false;
  42548. };
  42549. /**
  42550. * Makes a duplicate of the current material.
  42551. * @param name - name to use for the new material.
  42552. */
  42553. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  42554. var _this = this;
  42555. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  42556. clone.id = name;
  42557. clone.name = name;
  42558. return clone;
  42559. };
  42560. /**
  42561. * Serialize the material to a parsable JSON object.
  42562. */
  42563. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  42564. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42565. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  42566. return serializationObject;
  42567. };
  42568. /**
  42569. * Parses a JSON object correponding to the serialize function.
  42570. */
  42571. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  42572. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  42573. };
  42574. __decorate([
  42575. BABYLON.serializeAsColor3(),
  42576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42577. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  42578. __decorate([
  42579. BABYLON.serializeAsTexture(),
  42580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42581. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  42582. __decorate([
  42583. BABYLON.serialize(),
  42584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42585. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  42586. __decorate([
  42587. BABYLON.serialize(),
  42588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42589. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  42590. __decorate([
  42591. BABYLON.serializeAsTexture(),
  42592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  42593. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  42594. return PBRMetallicRoughnessMaterial;
  42595. }(BABYLON.PBRBaseSimpleMaterial));
  42596. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  42597. })(BABYLON || (BABYLON = {}));
  42598. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  42599. var BABYLON;
  42600. (function (BABYLON) {
  42601. /**
  42602. * The PBR material of BJS following the specular glossiness convention.
  42603. *
  42604. * This fits to the PBR convention in the GLTF definition:
  42605. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  42606. */
  42607. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  42608. __extends(PBRSpecularGlossinessMaterial, _super);
  42609. /**
  42610. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  42611. *
  42612. * @param name The material name
  42613. * @param scene The scene the material will be use in.
  42614. */
  42615. function PBRSpecularGlossinessMaterial(name, scene) {
  42616. var _this = _super.call(this, name, scene) || this;
  42617. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  42618. return _this;
  42619. }
  42620. /**
  42621. * Return the currrent class name of the material.
  42622. */
  42623. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  42624. return "PBRSpecularGlossinessMaterial";
  42625. };
  42626. /**
  42627. * Return the active textures of the material.
  42628. */
  42629. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  42630. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42631. if (this.diffuseTexture) {
  42632. activeTextures.push(this.diffuseTexture);
  42633. }
  42634. if (this.specularGlossinessTexture) {
  42635. activeTextures.push(this.specularGlossinessTexture);
  42636. }
  42637. return activeTextures;
  42638. };
  42639. /**
  42640. * Checks to see if a texture is used in the material.
  42641. * @param texture - Base texture to use.
  42642. * @returns - Boolean specifying if a texture is used in the material.
  42643. */
  42644. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  42645. if (_super.prototype.hasTexture.call(this, texture)) {
  42646. return true;
  42647. }
  42648. if (this.diffuseTexture === texture) {
  42649. return true;
  42650. }
  42651. if (this.specularGlossinessTexture === texture) {
  42652. return true;
  42653. }
  42654. return false;
  42655. };
  42656. /**
  42657. * Makes a duplicate of the current material.
  42658. * @param name - name to use for the new material.
  42659. */
  42660. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  42661. var _this = this;
  42662. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  42663. clone.id = name;
  42664. clone.name = name;
  42665. return clone;
  42666. };
  42667. /**
  42668. * Serialize the material to a parsable JSON object.
  42669. */
  42670. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  42671. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42672. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  42673. return serializationObject;
  42674. };
  42675. /**
  42676. * Parses a JSON object correponding to the serialize function.
  42677. */
  42678. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  42679. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  42680. };
  42681. __decorate([
  42682. BABYLON.serializeAsColor3("diffuse"),
  42683. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42684. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  42685. __decorate([
  42686. BABYLON.serializeAsTexture(),
  42687. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42688. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  42689. __decorate([
  42690. BABYLON.serializeAsColor3("specular"),
  42691. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  42692. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  42693. __decorate([
  42694. BABYLON.serialize(),
  42695. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  42696. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  42697. __decorate([
  42698. BABYLON.serializeAsTexture(),
  42699. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  42700. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  42701. return PBRSpecularGlossinessMaterial;
  42702. }(BABYLON.PBRBaseSimpleMaterial));
  42703. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  42704. })(BABYLON || (BABYLON = {}));
  42705. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  42706. var BABYLON;
  42707. (function (BABYLON) {
  42708. BABYLON.CameraInputTypes = {};
  42709. var CameraInputsManager = /** @class */ (function () {
  42710. function CameraInputsManager(camera) {
  42711. this.attached = {};
  42712. this.camera = camera;
  42713. this.checkInputs = function () { };
  42714. }
  42715. /**
  42716. * Add an input method to a camera.
  42717. * builtin inputs example: camera.inputs.addGamepad();
  42718. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  42719. * @param input camera input method
  42720. */
  42721. CameraInputsManager.prototype.add = function (input) {
  42722. var type = input.getSimpleName();
  42723. if (this.attached[type]) {
  42724. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  42725. return;
  42726. }
  42727. this.attached[type] = input;
  42728. input.camera = this.camera;
  42729. //for checkInputs, we are dynamically creating a function
  42730. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  42731. if (input.checkInputs) {
  42732. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42733. }
  42734. if (this.attachedElement) {
  42735. input.attachControl(this.attachedElement);
  42736. }
  42737. };
  42738. /**
  42739. * Remove a specific input method from a camera
  42740. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  42741. * @param inputToRemove camera input method
  42742. */
  42743. CameraInputsManager.prototype.remove = function (inputToRemove) {
  42744. for (var cam in this.attached) {
  42745. var input = this.attached[cam];
  42746. if (input === inputToRemove) {
  42747. input.detachControl(this.attachedElement);
  42748. input.camera = null;
  42749. delete this.attached[cam];
  42750. this.rebuildInputCheck();
  42751. }
  42752. }
  42753. };
  42754. CameraInputsManager.prototype.removeByType = function (inputType) {
  42755. for (var cam in this.attached) {
  42756. var input = this.attached[cam];
  42757. if (input.getClassName() === inputType) {
  42758. input.detachControl(this.attachedElement);
  42759. input.camera = null;
  42760. delete this.attached[cam];
  42761. this.rebuildInputCheck();
  42762. }
  42763. }
  42764. };
  42765. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  42766. var current = this.checkInputs;
  42767. return function () {
  42768. current();
  42769. fn();
  42770. };
  42771. };
  42772. CameraInputsManager.prototype.attachInput = function (input) {
  42773. if (this.attachedElement) {
  42774. input.attachControl(this.attachedElement, this.noPreventDefault);
  42775. }
  42776. };
  42777. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  42778. if (noPreventDefault === void 0) { noPreventDefault = false; }
  42779. if (this.attachedElement) {
  42780. return;
  42781. }
  42782. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  42783. this.attachedElement = element;
  42784. this.noPreventDefault = noPreventDefault;
  42785. for (var cam in this.attached) {
  42786. this.attached[cam].attachControl(element, noPreventDefault);
  42787. }
  42788. };
  42789. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  42790. if (disconnect === void 0) { disconnect = false; }
  42791. if (this.attachedElement !== element) {
  42792. return;
  42793. }
  42794. for (var cam in this.attached) {
  42795. this.attached[cam].detachControl(element);
  42796. if (disconnect) {
  42797. this.attached[cam].camera = null;
  42798. }
  42799. }
  42800. this.attachedElement = null;
  42801. };
  42802. CameraInputsManager.prototype.rebuildInputCheck = function () {
  42803. this.checkInputs = function () { };
  42804. for (var cam in this.attached) {
  42805. var input = this.attached[cam];
  42806. if (input.checkInputs) {
  42807. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42808. }
  42809. }
  42810. };
  42811. /**
  42812. * Remove all attached input methods from a camera
  42813. */
  42814. CameraInputsManager.prototype.clear = function () {
  42815. if (this.attachedElement) {
  42816. this.detachElement(this.attachedElement, true);
  42817. }
  42818. this.attached = {};
  42819. this.attachedElement = null;
  42820. this.checkInputs = function () { };
  42821. };
  42822. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  42823. var inputs = {};
  42824. for (var cam in this.attached) {
  42825. var input = this.attached[cam];
  42826. var res = BABYLON.SerializationHelper.Serialize(input);
  42827. inputs[input.getClassName()] = res;
  42828. }
  42829. serializedCamera.inputsmgr = inputs;
  42830. };
  42831. CameraInputsManager.prototype.parse = function (parsedCamera) {
  42832. var parsedInputs = parsedCamera.inputsmgr;
  42833. if (parsedInputs) {
  42834. this.clear();
  42835. for (var n in parsedInputs) {
  42836. var construct = BABYLON.CameraInputTypes[n];
  42837. if (construct) {
  42838. var parsedinput = parsedInputs[n];
  42839. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  42840. this.add(input);
  42841. }
  42842. }
  42843. }
  42844. else {
  42845. //2016-03-08 this part is for managing backward compatibility
  42846. for (var n in this.attached) {
  42847. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  42848. if (construct) {
  42849. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  42850. this.remove(this.attached[n]);
  42851. this.add(input);
  42852. }
  42853. }
  42854. }
  42855. };
  42856. return CameraInputsManager;
  42857. }());
  42858. BABYLON.CameraInputsManager = CameraInputsManager;
  42859. })(BABYLON || (BABYLON = {}));
  42860. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  42861. var BABYLON;
  42862. (function (BABYLON) {
  42863. var TargetCamera = /** @class */ (function (_super) {
  42864. __extends(TargetCamera, _super);
  42865. function TargetCamera(name, position, scene) {
  42866. var _this = _super.call(this, name, position, scene) || this;
  42867. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  42868. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  42869. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  42870. _this.speed = 2.0;
  42871. _this.noRotationConstraint = false;
  42872. _this.lockedTarget = null;
  42873. _this._currentTarget = BABYLON.Vector3.Zero();
  42874. _this._viewMatrix = BABYLON.Matrix.Zero();
  42875. _this._camMatrix = BABYLON.Matrix.Zero();
  42876. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  42877. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  42878. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  42879. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  42880. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  42881. _this._lookAtTemp = BABYLON.Matrix.Zero();
  42882. _this._tempMatrix = BABYLON.Matrix.Zero();
  42883. return _this;
  42884. }
  42885. TargetCamera.prototype.getFrontPosition = function (distance) {
  42886. this.getWorldMatrix();
  42887. var direction = this.getTarget().subtract(this.position);
  42888. direction.normalize();
  42889. direction.scaleInPlace(distance);
  42890. return this.globalPosition.add(direction);
  42891. };
  42892. TargetCamera.prototype._getLockedTargetPosition = function () {
  42893. if (!this.lockedTarget) {
  42894. return null;
  42895. }
  42896. if (this.lockedTarget.absolutePosition) {
  42897. this.lockedTarget.computeWorldMatrix();
  42898. }
  42899. return this.lockedTarget.absolutePosition || this.lockedTarget;
  42900. };
  42901. TargetCamera.prototype.storeState = function () {
  42902. this._storedPosition = this.position.clone();
  42903. this._storedRotation = this.rotation.clone();
  42904. if (this.rotationQuaternion) {
  42905. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  42906. }
  42907. return _super.prototype.storeState.call(this);
  42908. };
  42909. /**
  42910. * Restored camera state. You must call storeState() first
  42911. */
  42912. TargetCamera.prototype._restoreStateValues = function () {
  42913. if (!_super.prototype._restoreStateValues.call(this)) {
  42914. return false;
  42915. }
  42916. this.position = this._storedPosition.clone();
  42917. this.rotation = this._storedRotation.clone();
  42918. if (this.rotationQuaternion) {
  42919. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  42920. }
  42921. this.cameraDirection.copyFromFloats(0, 0, 0);
  42922. this.cameraRotation.copyFromFloats(0, 0);
  42923. return true;
  42924. };
  42925. // Cache
  42926. TargetCamera.prototype._initCache = function () {
  42927. _super.prototype._initCache.call(this);
  42928. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42929. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42930. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42931. };
  42932. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  42933. if (!ignoreParentClass) {
  42934. _super.prototype._updateCache.call(this);
  42935. }
  42936. var lockedTargetPosition = this._getLockedTargetPosition();
  42937. if (!lockedTargetPosition) {
  42938. this._cache.lockedTarget = null;
  42939. }
  42940. else {
  42941. if (!this._cache.lockedTarget) {
  42942. this._cache.lockedTarget = lockedTargetPosition.clone();
  42943. }
  42944. else {
  42945. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  42946. }
  42947. }
  42948. this._cache.rotation.copyFrom(this.rotation);
  42949. if (this.rotationQuaternion)
  42950. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42951. };
  42952. // Synchronized
  42953. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  42954. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  42955. return false;
  42956. }
  42957. var lockedTargetPosition = this._getLockedTargetPosition();
  42958. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  42959. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  42960. };
  42961. // Methods
  42962. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  42963. var engine = this.getEngine();
  42964. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  42965. };
  42966. // Target
  42967. TargetCamera.prototype.setTarget = function (target) {
  42968. this.upVector.normalize();
  42969. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  42970. this._camMatrix.invert();
  42971. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  42972. var vDir = target.subtract(this.position);
  42973. if (vDir.x >= 0.0) {
  42974. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  42975. }
  42976. else {
  42977. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  42978. }
  42979. this.rotation.z = 0;
  42980. if (isNaN(this.rotation.x)) {
  42981. this.rotation.x = 0;
  42982. }
  42983. if (isNaN(this.rotation.y)) {
  42984. this.rotation.y = 0;
  42985. }
  42986. if (isNaN(this.rotation.z)) {
  42987. this.rotation.z = 0;
  42988. }
  42989. if (this.rotationQuaternion) {
  42990. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  42991. }
  42992. };
  42993. /**
  42994. * Return the current target position of the camera. This value is expressed in local space.
  42995. */
  42996. TargetCamera.prototype.getTarget = function () {
  42997. return this._currentTarget;
  42998. };
  42999. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43000. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43001. };
  43002. TargetCamera.prototype._updatePosition = function () {
  43003. if (this.parent) {
  43004. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43005. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43006. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43007. return;
  43008. }
  43009. this.position.addInPlace(this.cameraDirection);
  43010. };
  43011. TargetCamera.prototype._checkInputs = function () {
  43012. var needToMove = this._decideIfNeedsToMove();
  43013. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43014. // Move
  43015. if (needToMove) {
  43016. this._updatePosition();
  43017. }
  43018. // Rotate
  43019. if (needToRotate) {
  43020. this.rotation.x += this.cameraRotation.x;
  43021. this.rotation.y += this.cameraRotation.y;
  43022. //rotate, if quaternion is set and rotation was used
  43023. if (this.rotationQuaternion) {
  43024. var len = this.rotation.lengthSquared();
  43025. if (len) {
  43026. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43027. }
  43028. }
  43029. if (!this.noRotationConstraint) {
  43030. var limit = (Math.PI / 2) * 0.95;
  43031. if (this.rotation.x > limit)
  43032. this.rotation.x = limit;
  43033. if (this.rotation.x < -limit)
  43034. this.rotation.x = -limit;
  43035. }
  43036. }
  43037. // Inertia
  43038. if (needToMove) {
  43039. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43040. this.cameraDirection.x = 0;
  43041. }
  43042. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43043. this.cameraDirection.y = 0;
  43044. }
  43045. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43046. this.cameraDirection.z = 0;
  43047. }
  43048. this.cameraDirection.scaleInPlace(this.inertia);
  43049. }
  43050. if (needToRotate) {
  43051. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43052. this.cameraRotation.x = 0;
  43053. }
  43054. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43055. this.cameraRotation.y = 0;
  43056. }
  43057. this.cameraRotation.scaleInPlace(this.inertia);
  43058. }
  43059. _super.prototype._checkInputs.call(this);
  43060. };
  43061. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43062. if (this.rotationQuaternion) {
  43063. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43064. }
  43065. else {
  43066. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43067. }
  43068. //update the up vector!
  43069. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43070. };
  43071. TargetCamera.prototype._getViewMatrix = function () {
  43072. if (this.lockedTarget) {
  43073. this.setTarget(this._getLockedTargetPosition());
  43074. }
  43075. // Compute
  43076. this._updateCameraRotationMatrix();
  43077. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43078. // Computing target and final matrix
  43079. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43080. if (this.getScene().useRightHandedSystem) {
  43081. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43082. }
  43083. else {
  43084. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43085. }
  43086. return this._viewMatrix;
  43087. };
  43088. /**
  43089. * @override
  43090. * Override Camera.createRigCamera
  43091. */
  43092. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43093. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43094. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43095. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43096. if (!this.rotationQuaternion) {
  43097. this.rotationQuaternion = new BABYLON.Quaternion();
  43098. }
  43099. rigCamera._cameraRigParams = {};
  43100. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43101. }
  43102. return rigCamera;
  43103. }
  43104. return null;
  43105. };
  43106. /**
  43107. * @override
  43108. * Override Camera._updateRigCameras
  43109. */
  43110. TargetCamera.prototype._updateRigCameras = function () {
  43111. var camLeft = this._rigCameras[0];
  43112. var camRight = this._rigCameras[1];
  43113. switch (this.cameraRigMode) {
  43114. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43115. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43116. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43117. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43118. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43119. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43120. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43121. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43122. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43123. camLeft.setTarget(this.getTarget());
  43124. camRight.setTarget(this.getTarget());
  43125. break;
  43126. case BABYLON.Camera.RIG_MODE_VR:
  43127. if (camLeft.rotationQuaternion) {
  43128. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43129. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43130. }
  43131. else {
  43132. camLeft.rotation.copyFrom(this.rotation);
  43133. camRight.rotation.copyFrom(this.rotation);
  43134. }
  43135. camLeft.position.copyFrom(this.position);
  43136. camRight.position.copyFrom(this.position);
  43137. break;
  43138. }
  43139. _super.prototype._updateRigCameras.call(this);
  43140. };
  43141. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43142. if (!this._rigCamTransformMatrix) {
  43143. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43144. }
  43145. var target = this.getTarget();
  43146. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43147. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43148. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43149. };
  43150. TargetCamera.prototype.getClassName = function () {
  43151. return "TargetCamera";
  43152. };
  43153. __decorate([
  43154. BABYLON.serializeAsVector3()
  43155. ], TargetCamera.prototype, "rotation", void 0);
  43156. __decorate([
  43157. BABYLON.serialize()
  43158. ], TargetCamera.prototype, "speed", void 0);
  43159. __decorate([
  43160. BABYLON.serializeAsMeshReference("lockedTargetId")
  43161. ], TargetCamera.prototype, "lockedTarget", void 0);
  43162. return TargetCamera;
  43163. }(BABYLON.Camera));
  43164. BABYLON.TargetCamera = TargetCamera;
  43165. })(BABYLON || (BABYLON = {}));
  43166. //# sourceMappingURL=babylon.targetCamera.js.map
  43167. var BABYLON;
  43168. (function (BABYLON) {
  43169. var FreeCameraMouseInput = /** @class */ (function () {
  43170. function FreeCameraMouseInput(touchEnabled) {
  43171. if (touchEnabled === void 0) { touchEnabled = true; }
  43172. this.touchEnabled = touchEnabled;
  43173. this.buttons = [0, 1, 2];
  43174. this.angularSensibility = 2000.0;
  43175. this.previousPosition = null;
  43176. }
  43177. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43178. var _this = this;
  43179. var engine = this.camera.getEngine();
  43180. if (!this._pointerInput) {
  43181. this._pointerInput = function (p, s) {
  43182. var evt = p.event;
  43183. if (engine.isInVRExclusivePointerMode) {
  43184. return;
  43185. }
  43186. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43187. return;
  43188. }
  43189. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43190. return;
  43191. }
  43192. var srcElement = (evt.srcElement || evt.target);
  43193. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43194. try {
  43195. srcElement.setPointerCapture(evt.pointerId);
  43196. }
  43197. catch (e) {
  43198. //Nothing to do with the error. Execution will continue.
  43199. }
  43200. _this.previousPosition = {
  43201. x: evt.clientX,
  43202. y: evt.clientY
  43203. };
  43204. if (!noPreventDefault) {
  43205. evt.preventDefault();
  43206. element.focus();
  43207. }
  43208. }
  43209. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43210. try {
  43211. srcElement.releasePointerCapture(evt.pointerId);
  43212. }
  43213. catch (e) {
  43214. //Nothing to do with the error.
  43215. }
  43216. _this.previousPosition = null;
  43217. if (!noPreventDefault) {
  43218. evt.preventDefault();
  43219. }
  43220. }
  43221. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43222. if (!_this.previousPosition || engine.isPointerLock) {
  43223. return;
  43224. }
  43225. var offsetX = evt.clientX - _this.previousPosition.x;
  43226. var offsetY = evt.clientY - _this.previousPosition.y;
  43227. if (_this.camera.getScene().useRightHandedSystem) {
  43228. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43229. }
  43230. else {
  43231. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43232. }
  43233. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43234. _this.previousPosition = {
  43235. x: evt.clientX,
  43236. y: evt.clientY
  43237. };
  43238. if (!noPreventDefault) {
  43239. evt.preventDefault();
  43240. }
  43241. }
  43242. };
  43243. }
  43244. this._onMouseMove = function (evt) {
  43245. if (!engine.isPointerLock) {
  43246. return;
  43247. }
  43248. if (engine.isInVRExclusivePointerMode) {
  43249. return;
  43250. }
  43251. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43252. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43253. if (_this.camera.getScene().useRightHandedSystem) {
  43254. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43255. }
  43256. else {
  43257. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43258. }
  43259. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43260. _this.previousPosition = null;
  43261. if (!noPreventDefault) {
  43262. evt.preventDefault();
  43263. }
  43264. };
  43265. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  43266. element.addEventListener("mousemove", this._onMouseMove, false);
  43267. };
  43268. FreeCameraMouseInput.prototype.detachControl = function (element) {
  43269. if (this._observer && element) {
  43270. this.camera.getScene().onPointerObservable.remove(this._observer);
  43271. if (this._onMouseMove) {
  43272. element.removeEventListener("mousemove", this._onMouseMove);
  43273. }
  43274. this._observer = null;
  43275. this._onMouseMove = null;
  43276. this.previousPosition = null;
  43277. }
  43278. };
  43279. FreeCameraMouseInput.prototype.getClassName = function () {
  43280. return "FreeCameraMouseInput";
  43281. };
  43282. FreeCameraMouseInput.prototype.getSimpleName = function () {
  43283. return "mouse";
  43284. };
  43285. __decorate([
  43286. BABYLON.serialize()
  43287. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  43288. __decorate([
  43289. BABYLON.serialize()
  43290. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  43291. return FreeCameraMouseInput;
  43292. }());
  43293. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  43294. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  43295. })(BABYLON || (BABYLON = {}));
  43296. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  43297. var BABYLON;
  43298. (function (BABYLON) {
  43299. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  43300. function FreeCameraKeyboardMoveInput() {
  43301. this._keys = new Array();
  43302. this.keysUp = [38];
  43303. this.keysDown = [40];
  43304. this.keysLeft = [37];
  43305. this.keysRight = [39];
  43306. }
  43307. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43308. var _this = this;
  43309. if (this._onCanvasBlurObserver) {
  43310. return;
  43311. }
  43312. this._scene = this.camera.getScene();
  43313. this._engine = this._scene.getEngine();
  43314. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43315. _this._keys = [];
  43316. });
  43317. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43318. var evt = info.event;
  43319. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43320. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43321. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43322. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43323. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43324. var index = _this._keys.indexOf(evt.keyCode);
  43325. if (index === -1) {
  43326. _this._keys.push(evt.keyCode);
  43327. }
  43328. if (!noPreventDefault) {
  43329. evt.preventDefault();
  43330. }
  43331. }
  43332. }
  43333. else {
  43334. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43335. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43336. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43337. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43338. var index = _this._keys.indexOf(evt.keyCode);
  43339. if (index >= 0) {
  43340. _this._keys.splice(index, 1);
  43341. }
  43342. if (!noPreventDefault) {
  43343. evt.preventDefault();
  43344. }
  43345. }
  43346. }
  43347. });
  43348. };
  43349. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43350. if (this._scene) {
  43351. if (this._onKeyboardObserver) {
  43352. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43353. }
  43354. if (this._onCanvasBlurObserver) {
  43355. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43356. }
  43357. this._onKeyboardObserver = null;
  43358. this._onCanvasBlurObserver = null;
  43359. }
  43360. this._keys = [];
  43361. };
  43362. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43363. if (this._onKeyboardObserver) {
  43364. var camera = this.camera;
  43365. // Keyboard
  43366. for (var index = 0; index < this._keys.length; index++) {
  43367. var keyCode = this._keys[index];
  43368. var speed = camera._computeLocalCameraSpeed();
  43369. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43370. camera._localDirection.copyFromFloats(-speed, 0, 0);
  43371. }
  43372. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43373. camera._localDirection.copyFromFloats(0, 0, speed);
  43374. }
  43375. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43376. camera._localDirection.copyFromFloats(speed, 0, 0);
  43377. }
  43378. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43379. camera._localDirection.copyFromFloats(0, 0, -speed);
  43380. }
  43381. if (camera.getScene().useRightHandedSystem) {
  43382. camera._localDirection.z *= -1;
  43383. }
  43384. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  43385. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  43386. camera.cameraDirection.addInPlace(camera._transformedDirection);
  43387. }
  43388. }
  43389. };
  43390. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  43391. return "FreeCameraKeyboardMoveInput";
  43392. };
  43393. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  43394. this._keys = [];
  43395. };
  43396. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43397. return "keyboard";
  43398. };
  43399. __decorate([
  43400. BABYLON.serialize()
  43401. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43402. __decorate([
  43403. BABYLON.serialize()
  43404. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43405. __decorate([
  43406. BABYLON.serialize()
  43407. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43408. __decorate([
  43409. BABYLON.serialize()
  43410. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43411. return FreeCameraKeyboardMoveInput;
  43412. }());
  43413. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  43414. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  43415. })(BABYLON || (BABYLON = {}));
  43416. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  43417. var BABYLON;
  43418. (function (BABYLON) {
  43419. var FreeCameraInputsManager = /** @class */ (function (_super) {
  43420. __extends(FreeCameraInputsManager, _super);
  43421. function FreeCameraInputsManager(camera) {
  43422. return _super.call(this, camera) || this;
  43423. }
  43424. FreeCameraInputsManager.prototype.addKeyboard = function () {
  43425. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  43426. return this;
  43427. };
  43428. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  43429. if (touchEnabled === void 0) { touchEnabled = true; }
  43430. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  43431. return this;
  43432. };
  43433. FreeCameraInputsManager.prototype.addGamepad = function () {
  43434. this.add(new BABYLON.FreeCameraGamepadInput());
  43435. return this;
  43436. };
  43437. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  43438. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  43439. return this;
  43440. };
  43441. FreeCameraInputsManager.prototype.addTouch = function () {
  43442. this.add(new BABYLON.FreeCameraTouchInput());
  43443. return this;
  43444. };
  43445. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  43446. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  43447. return this;
  43448. };
  43449. return FreeCameraInputsManager;
  43450. }(BABYLON.CameraInputsManager));
  43451. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  43452. })(BABYLON || (BABYLON = {}));
  43453. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  43454. var BABYLON;
  43455. (function (BABYLON) {
  43456. var FreeCamera = /** @class */ (function (_super) {
  43457. __extends(FreeCamera, _super);
  43458. function FreeCamera(name, position, scene) {
  43459. var _this = _super.call(this, name, position, scene) || this;
  43460. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  43461. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  43462. _this.checkCollisions = false;
  43463. _this.applyGravity = false;
  43464. _this._needMoveForGravity = false;
  43465. _this._oldPosition = BABYLON.Vector3.Zero();
  43466. _this._diffPosition = BABYLON.Vector3.Zero();
  43467. _this._newPosition = BABYLON.Vector3.Zero();
  43468. // Collisions
  43469. _this._collisionMask = -1;
  43470. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43471. if (collidedMesh === void 0) { collidedMesh = null; }
  43472. //TODO move this to the collision coordinator!
  43473. if (_this.getScene().workerCollisions)
  43474. newPosition.multiplyInPlace(_this._collider._radius);
  43475. var updatePosition = function (newPos) {
  43476. _this._newPosition.copyFrom(newPos);
  43477. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  43478. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  43479. _this.position.addInPlace(_this._diffPosition);
  43480. if (_this.onCollide && collidedMesh) {
  43481. _this.onCollide(collidedMesh);
  43482. }
  43483. }
  43484. };
  43485. updatePosition(newPosition);
  43486. };
  43487. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  43488. _this.inputs.addKeyboard().addMouse();
  43489. return _this;
  43490. }
  43491. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  43492. //-- begin properties for backward compatibility for inputs
  43493. /**
  43494. * Gets the input sensibility for a mouse input. (default is 2000.0)
  43495. * Higher values reduce sensitivity.
  43496. */
  43497. get: function () {
  43498. var mouse = this.inputs.attached["mouse"];
  43499. if (mouse)
  43500. return mouse.angularSensibility;
  43501. return 0;
  43502. },
  43503. /**
  43504. * Sets the input sensibility for a mouse input. (default is 2000.0)
  43505. * Higher values reduce sensitivity.
  43506. */
  43507. set: function (value) {
  43508. var mouse = this.inputs.attached["mouse"];
  43509. if (mouse)
  43510. mouse.angularSensibility = value;
  43511. },
  43512. enumerable: true,
  43513. configurable: true
  43514. });
  43515. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  43516. get: function () {
  43517. var keyboard = this.inputs.attached["keyboard"];
  43518. if (keyboard)
  43519. return keyboard.keysUp;
  43520. return [];
  43521. },
  43522. set: function (value) {
  43523. var keyboard = this.inputs.attached["keyboard"];
  43524. if (keyboard)
  43525. keyboard.keysUp = value;
  43526. },
  43527. enumerable: true,
  43528. configurable: true
  43529. });
  43530. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  43531. get: function () {
  43532. var keyboard = this.inputs.attached["keyboard"];
  43533. if (keyboard)
  43534. return keyboard.keysDown;
  43535. return [];
  43536. },
  43537. set: function (value) {
  43538. var keyboard = this.inputs.attached["keyboard"];
  43539. if (keyboard)
  43540. keyboard.keysDown = value;
  43541. },
  43542. enumerable: true,
  43543. configurable: true
  43544. });
  43545. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  43546. get: function () {
  43547. var keyboard = this.inputs.attached["keyboard"];
  43548. if (keyboard)
  43549. return keyboard.keysLeft;
  43550. return [];
  43551. },
  43552. set: function (value) {
  43553. var keyboard = this.inputs.attached["keyboard"];
  43554. if (keyboard)
  43555. keyboard.keysLeft = value;
  43556. },
  43557. enumerable: true,
  43558. configurable: true
  43559. });
  43560. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  43561. get: function () {
  43562. var keyboard = this.inputs.attached["keyboard"];
  43563. if (keyboard)
  43564. return keyboard.keysRight;
  43565. return [];
  43566. },
  43567. set: function (value) {
  43568. var keyboard = this.inputs.attached["keyboard"];
  43569. if (keyboard)
  43570. keyboard.keysRight = value;
  43571. },
  43572. enumerable: true,
  43573. configurable: true
  43574. });
  43575. // Controls
  43576. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  43577. this.inputs.attachElement(element, noPreventDefault);
  43578. };
  43579. FreeCamera.prototype.detachControl = function (element) {
  43580. this.inputs.detachElement(element);
  43581. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43582. this.cameraRotation = new BABYLON.Vector2(0, 0);
  43583. };
  43584. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  43585. get: function () {
  43586. return this._collisionMask;
  43587. },
  43588. set: function (mask) {
  43589. this._collisionMask = !isNaN(mask) ? mask : -1;
  43590. },
  43591. enumerable: true,
  43592. configurable: true
  43593. });
  43594. FreeCamera.prototype._collideWithWorld = function (displacement) {
  43595. var globalPosition;
  43596. if (this.parent) {
  43597. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  43598. }
  43599. else {
  43600. globalPosition = this.position;
  43601. }
  43602. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  43603. this._oldPosition.addInPlace(this.ellipsoidOffset);
  43604. if (!this._collider) {
  43605. this._collider = new BABYLON.Collider();
  43606. }
  43607. this._collider._radius = this.ellipsoid;
  43608. this._collider.collisionMask = this._collisionMask;
  43609. //no need for clone, as long as gravity is not on.
  43610. var actualDisplacement = displacement;
  43611. //add gravity to the direction to prevent the dual-collision checking
  43612. if (this.applyGravity) {
  43613. //this prevents mending with cameraDirection, a global variable of the free camera class.
  43614. actualDisplacement = displacement.add(this.getScene().gravity);
  43615. }
  43616. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  43617. };
  43618. FreeCamera.prototype._checkInputs = function () {
  43619. if (!this._localDirection) {
  43620. this._localDirection = BABYLON.Vector3.Zero();
  43621. this._transformedDirection = BABYLON.Vector3.Zero();
  43622. }
  43623. this.inputs.checkInputs();
  43624. _super.prototype._checkInputs.call(this);
  43625. };
  43626. FreeCamera.prototype._decideIfNeedsToMove = function () {
  43627. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43628. };
  43629. FreeCamera.prototype._updatePosition = function () {
  43630. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  43631. this._collideWithWorld(this.cameraDirection);
  43632. }
  43633. else {
  43634. _super.prototype._updatePosition.call(this);
  43635. }
  43636. };
  43637. FreeCamera.prototype.dispose = function () {
  43638. this.inputs.clear();
  43639. _super.prototype.dispose.call(this);
  43640. };
  43641. FreeCamera.prototype.getClassName = function () {
  43642. return "FreeCamera";
  43643. };
  43644. __decorate([
  43645. BABYLON.serializeAsVector3()
  43646. ], FreeCamera.prototype, "ellipsoid", void 0);
  43647. __decorate([
  43648. BABYLON.serializeAsVector3()
  43649. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  43650. __decorate([
  43651. BABYLON.serialize()
  43652. ], FreeCamera.prototype, "checkCollisions", void 0);
  43653. __decorate([
  43654. BABYLON.serialize()
  43655. ], FreeCamera.prototype, "applyGravity", void 0);
  43656. return FreeCamera;
  43657. }(BABYLON.TargetCamera));
  43658. BABYLON.FreeCamera = FreeCamera;
  43659. })(BABYLON || (BABYLON = {}));
  43660. //# sourceMappingURL=babylon.freeCamera.js.map
  43661. var BABYLON;
  43662. (function (BABYLON) {
  43663. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  43664. function ArcRotateCameraKeyboardMoveInput() {
  43665. this._keys = new Array();
  43666. this.keysUp = [38];
  43667. this.keysDown = [40];
  43668. this.keysLeft = [37];
  43669. this.keysRight = [39];
  43670. this.keysReset = [220];
  43671. this.panningSensibility = 50.0;
  43672. this.zoomingSensibility = 25.0;
  43673. this.useAltToZoom = true;
  43674. }
  43675. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43676. var _this = this;
  43677. if (this._onCanvasBlurObserver) {
  43678. return;
  43679. }
  43680. this._scene = this.camera.getScene();
  43681. this._engine = this._scene.getEngine();
  43682. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43683. _this._keys = [];
  43684. });
  43685. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43686. var evt = info.event;
  43687. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43688. _this._ctrlPressed = evt.ctrlKey;
  43689. _this._altPressed = evt.altKey;
  43690. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43691. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43692. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43693. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43694. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43695. var index = _this._keys.indexOf(evt.keyCode);
  43696. if (index === -1) {
  43697. _this._keys.push(evt.keyCode);
  43698. }
  43699. if (evt.preventDefault) {
  43700. if (!noPreventDefault) {
  43701. evt.preventDefault();
  43702. }
  43703. }
  43704. }
  43705. }
  43706. else {
  43707. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43708. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43709. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43710. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43711. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43712. var index = _this._keys.indexOf(evt.keyCode);
  43713. if (index >= 0) {
  43714. _this._keys.splice(index, 1);
  43715. }
  43716. if (evt.preventDefault) {
  43717. if (!noPreventDefault) {
  43718. evt.preventDefault();
  43719. }
  43720. }
  43721. }
  43722. }
  43723. });
  43724. };
  43725. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43726. if (this._scene) {
  43727. if (this._onKeyboardObserver) {
  43728. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43729. }
  43730. if (this._onCanvasBlurObserver) {
  43731. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43732. }
  43733. this._onKeyboardObserver = null;
  43734. this._onCanvasBlurObserver = null;
  43735. }
  43736. this._keys = [];
  43737. };
  43738. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43739. if (this._onKeyboardObserver) {
  43740. var camera = this.camera;
  43741. for (var index = 0; index < this._keys.length; index++) {
  43742. var keyCode = this._keys[index];
  43743. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43744. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43745. camera.inertialPanningX -= 1 / this.panningSensibility;
  43746. }
  43747. else {
  43748. camera.inertialAlphaOffset -= 0.01;
  43749. }
  43750. }
  43751. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43752. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43753. camera.inertialPanningY += 1 / this.panningSensibility;
  43754. }
  43755. else if (this._altPressed && this.useAltToZoom) {
  43756. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  43757. }
  43758. else {
  43759. camera.inertialBetaOffset -= 0.01;
  43760. }
  43761. }
  43762. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43763. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43764. camera.inertialPanningX += 1 / this.panningSensibility;
  43765. }
  43766. else {
  43767. camera.inertialAlphaOffset += 0.01;
  43768. }
  43769. }
  43770. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43771. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43772. camera.inertialPanningY -= 1 / this.panningSensibility;
  43773. }
  43774. else if (this._altPressed && this.useAltToZoom) {
  43775. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  43776. }
  43777. else {
  43778. camera.inertialBetaOffset += 0.01;
  43779. }
  43780. }
  43781. else if (this.keysReset.indexOf(keyCode) !== -1) {
  43782. camera.restoreState();
  43783. }
  43784. }
  43785. }
  43786. };
  43787. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  43788. return "ArcRotateCameraKeyboardMoveInput";
  43789. };
  43790. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43791. return "keyboard";
  43792. };
  43793. __decorate([
  43794. BABYLON.serialize()
  43795. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43796. __decorate([
  43797. BABYLON.serialize()
  43798. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43799. __decorate([
  43800. BABYLON.serialize()
  43801. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43802. __decorate([
  43803. BABYLON.serialize()
  43804. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43805. __decorate([
  43806. BABYLON.serialize()
  43807. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  43808. __decorate([
  43809. BABYLON.serialize()
  43810. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  43811. __decorate([
  43812. BABYLON.serialize()
  43813. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  43814. __decorate([
  43815. BABYLON.serialize()
  43816. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  43817. return ArcRotateCameraKeyboardMoveInput;
  43818. }());
  43819. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  43820. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  43821. })(BABYLON || (BABYLON = {}));
  43822. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  43823. var BABYLON;
  43824. (function (BABYLON) {
  43825. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  43826. function ArcRotateCameraMouseWheelInput() {
  43827. this.wheelPrecision = 3.0;
  43828. /**
  43829. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  43830. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  43831. */
  43832. this.wheelDeltaPercentage = 0;
  43833. }
  43834. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  43835. var _this = this;
  43836. this._wheel = function (p, s) {
  43837. //sanity check - this should be a PointerWheel event.
  43838. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  43839. return;
  43840. var event = p.event;
  43841. var delta = 0;
  43842. if (event.wheelDelta) {
  43843. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  43844. }
  43845. else if (event.detail) {
  43846. delta = -event.detail / _this.wheelPrecision;
  43847. }
  43848. if (delta)
  43849. _this.camera.inertialRadiusOffset += delta;
  43850. if (event.preventDefault) {
  43851. if (!noPreventDefault) {
  43852. event.preventDefault();
  43853. }
  43854. }
  43855. };
  43856. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  43857. };
  43858. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  43859. if (this._observer && element) {
  43860. this.camera.getScene().onPointerObservable.remove(this._observer);
  43861. this._observer = null;
  43862. this._wheel = null;
  43863. }
  43864. };
  43865. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  43866. return "ArcRotateCameraMouseWheelInput";
  43867. };
  43868. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  43869. return "mousewheel";
  43870. };
  43871. __decorate([
  43872. BABYLON.serialize()
  43873. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  43874. __decorate([
  43875. BABYLON.serialize()
  43876. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  43877. return ArcRotateCameraMouseWheelInput;
  43878. }());
  43879. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  43880. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  43881. })(BABYLON || (BABYLON = {}));
  43882. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  43883. var BABYLON;
  43884. (function (BABYLON) {
  43885. var ArcRotateCameraPointersInput = /** @class */ (function () {
  43886. function ArcRotateCameraPointersInput() {
  43887. this.buttons = [0, 1, 2];
  43888. this.angularSensibilityX = 1000.0;
  43889. this.angularSensibilityY = 1000.0;
  43890. this.pinchPrecision = 12.0;
  43891. /**
  43892. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  43893. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  43894. */
  43895. this.pinchDeltaPercentage = 0;
  43896. this.panningSensibility = 1000.0;
  43897. this.multiTouchPanning = true;
  43898. this.multiTouchPanAndZoom = true;
  43899. this._isPanClick = false;
  43900. this.pinchInwards = true;
  43901. }
  43902. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  43903. var _this = this;
  43904. var engine = this.camera.getEngine();
  43905. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  43906. var pointA = null;
  43907. var pointB = null;
  43908. var previousPinchSquaredDistance = 0;
  43909. var initialDistance = 0;
  43910. var twoFingerActivityCount = 0;
  43911. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  43912. this._pointerInput = function (p, s) {
  43913. var evt = p.event;
  43914. var isTouch = p.event.pointerType === "touch";
  43915. if (engine.isInVRExclusivePointerMode) {
  43916. return;
  43917. }
  43918. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43919. return;
  43920. }
  43921. var srcElement = (evt.srcElement || evt.target);
  43922. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43923. try {
  43924. srcElement.setPointerCapture(evt.pointerId);
  43925. }
  43926. catch (e) {
  43927. //Nothing to do with the error. Execution will continue.
  43928. }
  43929. // Manage panning with pan button click
  43930. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  43931. // manage pointers
  43932. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  43933. if (pointA === null) {
  43934. pointA = cacheSoloPointer;
  43935. }
  43936. else if (pointB === null) {
  43937. pointB = cacheSoloPointer;
  43938. }
  43939. if (!noPreventDefault) {
  43940. evt.preventDefault();
  43941. element.focus();
  43942. }
  43943. }
  43944. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  43945. _this.camera.restoreState();
  43946. }
  43947. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43948. try {
  43949. srcElement.releasePointerCapture(evt.pointerId);
  43950. }
  43951. catch (e) {
  43952. //Nothing to do with the error.
  43953. }
  43954. cacheSoloPointer = null;
  43955. previousPinchSquaredDistance = 0;
  43956. previousMultiTouchPanPosition.isPaning = false;
  43957. previousMultiTouchPanPosition.isPinching = false;
  43958. twoFingerActivityCount = 0;
  43959. initialDistance = 0;
  43960. if (!isTouch) {
  43961. pointB = null; // Mouse and pen are mono pointer
  43962. }
  43963. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  43964. //but emptying completly pointers collection is required to fix a bug on iPhone :
  43965. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  43966. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  43967. if (engine.badOS) {
  43968. pointA = pointB = null;
  43969. }
  43970. else {
  43971. //only remove the impacted pointer in case of multitouch allowing on most
  43972. //platforms switching from rotate to zoom and pan seamlessly.
  43973. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  43974. pointA = pointB;
  43975. pointB = null;
  43976. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  43977. }
  43978. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  43979. pointB = null;
  43980. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  43981. }
  43982. else {
  43983. pointA = pointB = null;
  43984. }
  43985. }
  43986. if (!noPreventDefault) {
  43987. evt.preventDefault();
  43988. }
  43989. }
  43990. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43991. if (!noPreventDefault) {
  43992. evt.preventDefault();
  43993. }
  43994. // One button down
  43995. if (pointA && pointB === null && cacheSoloPointer) {
  43996. if (_this.panningSensibility !== 0 &&
  43997. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  43998. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  43999. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44000. }
  44001. else {
  44002. var offsetX = evt.clientX - cacheSoloPointer.x;
  44003. var offsetY = evt.clientY - cacheSoloPointer.y;
  44004. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44005. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44006. }
  44007. cacheSoloPointer.x = evt.clientX;
  44008. cacheSoloPointer.y = evt.clientY;
  44009. }
  44010. else if (pointA && pointB) {
  44011. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44012. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44013. ed.x = evt.clientX;
  44014. ed.y = evt.clientY;
  44015. var direction = _this.pinchInwards ? 1 : -1;
  44016. var distX = pointA.x - pointB.x;
  44017. var distY = pointA.y - pointB.y;
  44018. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44019. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44020. if (previousPinchSquaredDistance === 0) {
  44021. initialDistance = pinchDistance;
  44022. previousPinchSquaredDistance = pinchSquaredDistance;
  44023. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44024. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44025. return;
  44026. }
  44027. if (_this.multiTouchPanAndZoom) {
  44028. if (_this.pinchDeltaPercentage) {
  44029. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44030. }
  44031. else {
  44032. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44033. (_this.pinchPrecision *
  44034. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44035. direction);
  44036. }
  44037. if (_this.panningSensibility !== 0) {
  44038. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44039. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44040. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44041. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44042. previousMultiTouchPanPosition.x = pointersCenterX;
  44043. previousMultiTouchPanPosition.y = pointersCenterY;
  44044. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44045. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44046. }
  44047. }
  44048. else {
  44049. twoFingerActivityCount++;
  44050. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44051. if (_this.pinchDeltaPercentage) {
  44052. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44053. }
  44054. else {
  44055. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44056. (_this.pinchPrecision *
  44057. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44058. direction);
  44059. }
  44060. previousMultiTouchPanPosition.isPaning = false;
  44061. previousMultiTouchPanPosition.isPinching = true;
  44062. }
  44063. else {
  44064. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44065. if (!previousMultiTouchPanPosition.isPaning) {
  44066. previousMultiTouchPanPosition.isPaning = true;
  44067. previousMultiTouchPanPosition.isPinching = false;
  44068. previousMultiTouchPanPosition.x = ed.x;
  44069. previousMultiTouchPanPosition.y = ed.y;
  44070. return;
  44071. }
  44072. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44073. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44074. }
  44075. }
  44076. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44077. previousMultiTouchPanPosition.x = ed.x;
  44078. previousMultiTouchPanPosition.y = ed.y;
  44079. }
  44080. }
  44081. previousPinchSquaredDistance = pinchSquaredDistance;
  44082. }
  44083. }
  44084. };
  44085. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44086. this._onContextMenu = function (evt) {
  44087. evt.preventDefault();
  44088. };
  44089. if (!this.camera._useCtrlForPanning) {
  44090. element.addEventListener("contextmenu", this._onContextMenu, false);
  44091. }
  44092. this._onLostFocus = function () {
  44093. //this._keys = [];
  44094. pointA = pointB = null;
  44095. previousPinchSquaredDistance = 0;
  44096. previousMultiTouchPanPosition.isPaning = false;
  44097. previousMultiTouchPanPosition.isPinching = false;
  44098. twoFingerActivityCount = 0;
  44099. cacheSoloPointer = null;
  44100. initialDistance = 0;
  44101. };
  44102. this._onMouseMove = function (evt) {
  44103. if (!engine.isPointerLock) {
  44104. return;
  44105. }
  44106. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44107. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44108. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44109. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44110. if (!noPreventDefault) {
  44111. evt.preventDefault();
  44112. }
  44113. };
  44114. this._onGestureStart = function (e) {
  44115. if (window.MSGesture === undefined) {
  44116. return;
  44117. }
  44118. if (!_this._MSGestureHandler) {
  44119. _this._MSGestureHandler = new MSGesture();
  44120. _this._MSGestureHandler.target = element;
  44121. }
  44122. _this._MSGestureHandler.addPointer(e.pointerId);
  44123. };
  44124. this._onGesture = function (e) {
  44125. _this.camera.radius *= e.scale;
  44126. if (e.preventDefault) {
  44127. if (!noPreventDefault) {
  44128. e.stopPropagation();
  44129. e.preventDefault();
  44130. }
  44131. }
  44132. };
  44133. element.addEventListener("mousemove", this._onMouseMove, false);
  44134. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44135. element.addEventListener("MSGestureChange", this._onGesture, false);
  44136. BABYLON.Tools.RegisterTopRootEvents([
  44137. { name: "blur", handler: this._onLostFocus }
  44138. ]);
  44139. };
  44140. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44141. if (this._onLostFocus) {
  44142. BABYLON.Tools.UnregisterTopRootEvents([
  44143. { name: "blur", handler: this._onLostFocus }
  44144. ]);
  44145. }
  44146. if (element && this._observer) {
  44147. this.camera.getScene().onPointerObservable.remove(this._observer);
  44148. this._observer = null;
  44149. if (this._onContextMenu) {
  44150. element.removeEventListener("contextmenu", this._onContextMenu);
  44151. }
  44152. if (this._onMouseMove) {
  44153. element.removeEventListener("mousemove", this._onMouseMove);
  44154. }
  44155. if (this._onGestureStart) {
  44156. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44157. }
  44158. if (this._onGesture) {
  44159. element.removeEventListener("MSGestureChange", this._onGesture);
  44160. }
  44161. this._isPanClick = false;
  44162. this.pinchInwards = true;
  44163. this._onMouseMove = null;
  44164. this._onGestureStart = null;
  44165. this._onGesture = null;
  44166. this._MSGestureHandler = null;
  44167. this._onLostFocus = null;
  44168. this._onContextMenu = null;
  44169. }
  44170. };
  44171. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44172. return "ArcRotateCameraPointersInput";
  44173. };
  44174. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44175. return "pointers";
  44176. };
  44177. __decorate([
  44178. BABYLON.serialize()
  44179. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44180. __decorate([
  44181. BABYLON.serialize()
  44182. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  44183. __decorate([
  44184. BABYLON.serialize()
  44185. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  44186. __decorate([
  44187. BABYLON.serialize()
  44188. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  44189. __decorate([
  44190. BABYLON.serialize()
  44191. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  44192. __decorate([
  44193. BABYLON.serialize()
  44194. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  44195. __decorate([
  44196. BABYLON.serialize()
  44197. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  44198. __decorate([
  44199. BABYLON.serialize()
  44200. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  44201. return ArcRotateCameraPointersInput;
  44202. }());
  44203. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  44204. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  44205. })(BABYLON || (BABYLON = {}));
  44206. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  44207. var BABYLON;
  44208. (function (BABYLON) {
  44209. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  44210. __extends(ArcRotateCameraInputsManager, _super);
  44211. function ArcRotateCameraInputsManager(camera) {
  44212. return _super.call(this, camera) || this;
  44213. }
  44214. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  44215. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  44216. return this;
  44217. };
  44218. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  44219. this.add(new BABYLON.ArcRotateCameraPointersInput());
  44220. return this;
  44221. };
  44222. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  44223. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  44224. return this;
  44225. };
  44226. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  44227. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  44228. return this;
  44229. };
  44230. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  44231. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  44232. return this;
  44233. };
  44234. return ArcRotateCameraInputsManager;
  44235. }(BABYLON.CameraInputsManager));
  44236. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  44237. })(BABYLON || (BABYLON = {}));
  44238. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  44239. var BABYLON;
  44240. (function (BABYLON) {
  44241. var ArcRotateCamera = /** @class */ (function (_super) {
  44242. __extends(ArcRotateCamera, _super);
  44243. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  44244. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  44245. _this.inertialAlphaOffset = 0;
  44246. _this.inertialBetaOffset = 0;
  44247. _this.inertialRadiusOffset = 0;
  44248. _this.lowerAlphaLimit = null;
  44249. _this.upperAlphaLimit = null;
  44250. _this.lowerBetaLimit = 0.01;
  44251. _this.upperBetaLimit = Math.PI;
  44252. _this.lowerRadiusLimit = null;
  44253. _this.upperRadiusLimit = null;
  44254. _this.inertialPanningX = 0;
  44255. _this.inertialPanningY = 0;
  44256. _this.pinchToPanMaxDistance = 20;
  44257. _this.panningDistanceLimit = null;
  44258. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  44259. _this.panningInertia = 0.9;
  44260. //-- end properties for backward compatibility for inputs
  44261. _this.zoomOnFactor = 1;
  44262. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  44263. _this.allowUpsideDown = true;
  44264. _this._viewMatrix = new BABYLON.Matrix();
  44265. // Panning
  44266. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  44267. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  44268. _this.checkCollisions = false;
  44269. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44270. _this._previousPosition = BABYLON.Vector3.Zero();
  44271. _this._collisionVelocity = BABYLON.Vector3.Zero();
  44272. _this._newPosition = BABYLON.Vector3.Zero();
  44273. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44274. if (collidedMesh === void 0) { collidedMesh = null; }
  44275. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  44276. newPosition.multiplyInPlace(_this._collider._radius);
  44277. }
  44278. if (!collidedMesh) {
  44279. _this._previousPosition.copyFrom(_this.position);
  44280. }
  44281. else {
  44282. _this.setPosition(newPosition);
  44283. if (_this.onCollide) {
  44284. _this.onCollide(collidedMesh);
  44285. }
  44286. }
  44287. // Recompute because of constraints
  44288. var cosa = Math.cos(_this.alpha);
  44289. var sina = Math.sin(_this.alpha);
  44290. var cosb = Math.cos(_this.beta);
  44291. var sinb = Math.sin(_this.beta);
  44292. if (sinb === 0) {
  44293. sinb = 0.0001;
  44294. }
  44295. var target = _this._getTargetPosition();
  44296. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  44297. _this.position.copyFrom(_this._newPosition);
  44298. var up = _this.upVector;
  44299. if (_this.allowUpsideDown && _this.beta < 0) {
  44300. up = up.clone();
  44301. up = up.negate();
  44302. }
  44303. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  44304. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  44305. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  44306. _this._collisionTriggered = false;
  44307. };
  44308. _this._target = BABYLON.Vector3.Zero();
  44309. if (target) {
  44310. _this.setTarget(target);
  44311. }
  44312. _this.alpha = alpha;
  44313. _this.beta = beta;
  44314. _this.radius = radius;
  44315. _this.getViewMatrix();
  44316. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  44317. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  44318. return _this;
  44319. }
  44320. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  44321. get: function () {
  44322. return this._target;
  44323. },
  44324. set: function (value) {
  44325. this.setTarget(value);
  44326. },
  44327. enumerable: true,
  44328. configurable: true
  44329. });
  44330. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  44331. //-- begin properties for backward compatibility for inputs
  44332. get: function () {
  44333. var pointers = this.inputs.attached["pointers"];
  44334. if (pointers)
  44335. return pointers.angularSensibilityX;
  44336. return 0;
  44337. },
  44338. set: function (value) {
  44339. var pointers = this.inputs.attached["pointers"];
  44340. if (pointers) {
  44341. pointers.angularSensibilityX = value;
  44342. }
  44343. },
  44344. enumerable: true,
  44345. configurable: true
  44346. });
  44347. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  44348. get: function () {
  44349. var pointers = this.inputs.attached["pointers"];
  44350. if (pointers)
  44351. return pointers.angularSensibilityY;
  44352. return 0;
  44353. },
  44354. set: function (value) {
  44355. var pointers = this.inputs.attached["pointers"];
  44356. if (pointers) {
  44357. pointers.angularSensibilityY = value;
  44358. }
  44359. },
  44360. enumerable: true,
  44361. configurable: true
  44362. });
  44363. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  44364. get: function () {
  44365. var pointers = this.inputs.attached["pointers"];
  44366. if (pointers)
  44367. return pointers.pinchPrecision;
  44368. return 0;
  44369. },
  44370. set: function (value) {
  44371. var pointers = this.inputs.attached["pointers"];
  44372. if (pointers) {
  44373. pointers.pinchPrecision = value;
  44374. }
  44375. },
  44376. enumerable: true,
  44377. configurable: true
  44378. });
  44379. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  44380. get: function () {
  44381. var pointers = this.inputs.attached["pointers"];
  44382. if (pointers)
  44383. return pointers.pinchDeltaPercentage;
  44384. return 0;
  44385. },
  44386. set: function (value) {
  44387. var pointers = this.inputs.attached["pointers"];
  44388. if (pointers) {
  44389. pointers.pinchDeltaPercentage = value;
  44390. }
  44391. },
  44392. enumerable: true,
  44393. configurable: true
  44394. });
  44395. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  44396. get: function () {
  44397. var pointers = this.inputs.attached["pointers"];
  44398. if (pointers)
  44399. return pointers.panningSensibility;
  44400. return 0;
  44401. },
  44402. set: function (value) {
  44403. var pointers = this.inputs.attached["pointers"];
  44404. if (pointers) {
  44405. pointers.panningSensibility = value;
  44406. }
  44407. },
  44408. enumerable: true,
  44409. configurable: true
  44410. });
  44411. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  44412. get: function () {
  44413. var keyboard = this.inputs.attached["keyboard"];
  44414. if (keyboard)
  44415. return keyboard.keysUp;
  44416. return [];
  44417. },
  44418. set: function (value) {
  44419. var keyboard = this.inputs.attached["keyboard"];
  44420. if (keyboard)
  44421. keyboard.keysUp = value;
  44422. },
  44423. enumerable: true,
  44424. configurable: true
  44425. });
  44426. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  44427. get: function () {
  44428. var keyboard = this.inputs.attached["keyboard"];
  44429. if (keyboard)
  44430. return keyboard.keysDown;
  44431. return [];
  44432. },
  44433. set: function (value) {
  44434. var keyboard = this.inputs.attached["keyboard"];
  44435. if (keyboard)
  44436. keyboard.keysDown = value;
  44437. },
  44438. enumerable: true,
  44439. configurable: true
  44440. });
  44441. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  44442. get: function () {
  44443. var keyboard = this.inputs.attached["keyboard"];
  44444. if (keyboard)
  44445. return keyboard.keysLeft;
  44446. return [];
  44447. },
  44448. set: function (value) {
  44449. var keyboard = this.inputs.attached["keyboard"];
  44450. if (keyboard)
  44451. keyboard.keysLeft = value;
  44452. },
  44453. enumerable: true,
  44454. configurable: true
  44455. });
  44456. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  44457. get: function () {
  44458. var keyboard = this.inputs.attached["keyboard"];
  44459. if (keyboard)
  44460. return keyboard.keysRight;
  44461. return [];
  44462. },
  44463. set: function (value) {
  44464. var keyboard = this.inputs.attached["keyboard"];
  44465. if (keyboard)
  44466. keyboard.keysRight = value;
  44467. },
  44468. enumerable: true,
  44469. configurable: true
  44470. });
  44471. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  44472. get: function () {
  44473. var mousewheel = this.inputs.attached["mousewheel"];
  44474. if (mousewheel)
  44475. return mousewheel.wheelPrecision;
  44476. return 0;
  44477. },
  44478. set: function (value) {
  44479. var mousewheel = this.inputs.attached["mousewheel"];
  44480. if (mousewheel)
  44481. mousewheel.wheelPrecision = value;
  44482. },
  44483. enumerable: true,
  44484. configurable: true
  44485. });
  44486. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  44487. get: function () {
  44488. var mousewheel = this.inputs.attached["mousewheel"];
  44489. if (mousewheel)
  44490. return mousewheel.wheelDeltaPercentage;
  44491. return 0;
  44492. },
  44493. set: function (value) {
  44494. var mousewheel = this.inputs.attached["mousewheel"];
  44495. if (mousewheel)
  44496. mousewheel.wheelDeltaPercentage = value;
  44497. },
  44498. enumerable: true,
  44499. configurable: true
  44500. });
  44501. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  44502. get: function () {
  44503. return this._bouncingBehavior;
  44504. },
  44505. enumerable: true,
  44506. configurable: true
  44507. });
  44508. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  44509. get: function () {
  44510. return this._bouncingBehavior != null;
  44511. },
  44512. set: function (value) {
  44513. if (value === this.useBouncingBehavior) {
  44514. return;
  44515. }
  44516. if (value) {
  44517. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  44518. this.addBehavior(this._bouncingBehavior);
  44519. }
  44520. else if (this._bouncingBehavior) {
  44521. this.removeBehavior(this._bouncingBehavior);
  44522. this._bouncingBehavior = null;
  44523. }
  44524. },
  44525. enumerable: true,
  44526. configurable: true
  44527. });
  44528. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  44529. get: function () {
  44530. return this._framingBehavior;
  44531. },
  44532. enumerable: true,
  44533. configurable: true
  44534. });
  44535. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  44536. get: function () {
  44537. return this._framingBehavior != null;
  44538. },
  44539. set: function (value) {
  44540. if (value === this.useFramingBehavior) {
  44541. return;
  44542. }
  44543. if (value) {
  44544. this._framingBehavior = new BABYLON.FramingBehavior();
  44545. this.addBehavior(this._framingBehavior);
  44546. }
  44547. else if (this._framingBehavior) {
  44548. this.removeBehavior(this._framingBehavior);
  44549. this._framingBehavior = null;
  44550. }
  44551. },
  44552. enumerable: true,
  44553. configurable: true
  44554. });
  44555. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  44556. get: function () {
  44557. return this._autoRotationBehavior;
  44558. },
  44559. enumerable: true,
  44560. configurable: true
  44561. });
  44562. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  44563. get: function () {
  44564. return this._autoRotationBehavior != null;
  44565. },
  44566. set: function (value) {
  44567. if (value === this.useAutoRotationBehavior) {
  44568. return;
  44569. }
  44570. if (value) {
  44571. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  44572. this.addBehavior(this._autoRotationBehavior);
  44573. }
  44574. else if (this._autoRotationBehavior) {
  44575. this.removeBehavior(this._autoRotationBehavior);
  44576. this._autoRotationBehavior = null;
  44577. }
  44578. },
  44579. enumerable: true,
  44580. configurable: true
  44581. });
  44582. // Cache
  44583. ArcRotateCamera.prototype._initCache = function () {
  44584. _super.prototype._initCache.call(this);
  44585. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  44586. this._cache.alpha = undefined;
  44587. this._cache.beta = undefined;
  44588. this._cache.radius = undefined;
  44589. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  44590. };
  44591. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  44592. if (!ignoreParentClass) {
  44593. _super.prototype._updateCache.call(this);
  44594. }
  44595. this._cache._target.copyFrom(this._getTargetPosition());
  44596. this._cache.alpha = this.alpha;
  44597. this._cache.beta = this.beta;
  44598. this._cache.radius = this.radius;
  44599. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  44600. };
  44601. ArcRotateCamera.prototype._getTargetPosition = function () {
  44602. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  44603. var pos = this._targetHost.getAbsolutePosition();
  44604. if (this._targetBoundingCenter) {
  44605. pos.addToRef(this._targetBoundingCenter, this._target);
  44606. }
  44607. else {
  44608. this._target.copyFrom(pos);
  44609. }
  44610. }
  44611. var lockedTargetPosition = this._getLockedTargetPosition();
  44612. if (lockedTargetPosition) {
  44613. return lockedTargetPosition;
  44614. }
  44615. return this._target;
  44616. };
  44617. ArcRotateCamera.prototype.storeState = function () {
  44618. this._storedAlpha = this.alpha;
  44619. this._storedBeta = this.beta;
  44620. this._storedRadius = this.radius;
  44621. this._storedTarget = this._getTargetPosition().clone();
  44622. return _super.prototype.storeState.call(this);
  44623. };
  44624. /**
  44625. * Restored camera state. You must call storeState() first
  44626. */
  44627. ArcRotateCamera.prototype._restoreStateValues = function () {
  44628. if (!_super.prototype._restoreStateValues.call(this)) {
  44629. return false;
  44630. }
  44631. this.alpha = this._storedAlpha;
  44632. this.beta = this._storedBeta;
  44633. this.radius = this._storedRadius;
  44634. this.setTarget(this._storedTarget.clone());
  44635. this.inertialAlphaOffset = 0;
  44636. this.inertialBetaOffset = 0;
  44637. this.inertialRadiusOffset = 0;
  44638. this.inertialPanningX = 0;
  44639. this.inertialPanningY = 0;
  44640. return true;
  44641. };
  44642. // Synchronized
  44643. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  44644. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  44645. return false;
  44646. return this._cache._target.equals(this._getTargetPosition())
  44647. && this._cache.alpha === this.alpha
  44648. && this._cache.beta === this.beta
  44649. && this._cache.radius === this.radius
  44650. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  44651. };
  44652. // Methods
  44653. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  44654. var _this = this;
  44655. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  44656. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  44657. this._useCtrlForPanning = useCtrlForPanning;
  44658. this._panningMouseButton = panningMouseButton;
  44659. this.inputs.attachElement(element, noPreventDefault);
  44660. this._reset = function () {
  44661. _this.inertialAlphaOffset = 0;
  44662. _this.inertialBetaOffset = 0;
  44663. _this.inertialRadiusOffset = 0;
  44664. _this.inertialPanningX = 0;
  44665. _this.inertialPanningY = 0;
  44666. };
  44667. };
  44668. ArcRotateCamera.prototype.detachControl = function (element) {
  44669. this.inputs.detachElement(element);
  44670. if (this._reset) {
  44671. this._reset();
  44672. }
  44673. };
  44674. ArcRotateCamera.prototype._checkInputs = function () {
  44675. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  44676. if (this._collisionTriggered) {
  44677. return;
  44678. }
  44679. this.inputs.checkInputs();
  44680. // Inertia
  44681. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  44682. if (this.getScene().useRightHandedSystem) {
  44683. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44684. }
  44685. else {
  44686. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44687. }
  44688. this.beta += this.inertialBetaOffset;
  44689. this.radius -= this.inertialRadiusOffset;
  44690. this.inertialAlphaOffset *= this.inertia;
  44691. this.inertialBetaOffset *= this.inertia;
  44692. this.inertialRadiusOffset *= this.inertia;
  44693. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  44694. this.inertialAlphaOffset = 0;
  44695. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  44696. this.inertialBetaOffset = 0;
  44697. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  44698. this.inertialRadiusOffset = 0;
  44699. }
  44700. // Panning inertia
  44701. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  44702. if (!this._localDirection) {
  44703. this._localDirection = BABYLON.Vector3.Zero();
  44704. this._transformedDirection = BABYLON.Vector3.Zero();
  44705. }
  44706. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  44707. this._localDirection.multiplyInPlace(this.panningAxis);
  44708. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  44709. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  44710. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  44711. if (!this.panningAxis.y) {
  44712. this._transformedDirection.y = 0;
  44713. }
  44714. if (!this._targetHost) {
  44715. if (this.panningDistanceLimit) {
  44716. this._transformedDirection.addInPlace(this._target);
  44717. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  44718. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  44719. this._target.copyFrom(this._transformedDirection);
  44720. }
  44721. }
  44722. else {
  44723. this._target.addInPlace(this._transformedDirection);
  44724. }
  44725. }
  44726. this.inertialPanningX *= this.panningInertia;
  44727. this.inertialPanningY *= this.panningInertia;
  44728. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  44729. this.inertialPanningX = 0;
  44730. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  44731. this.inertialPanningY = 0;
  44732. }
  44733. // Limits
  44734. this._checkLimits();
  44735. _super.prototype._checkInputs.call(this);
  44736. };
  44737. ArcRotateCamera.prototype._checkLimits = function () {
  44738. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  44739. if (this.allowUpsideDown && this.beta > Math.PI) {
  44740. this.beta = this.beta - (2 * Math.PI);
  44741. }
  44742. }
  44743. else {
  44744. if (this.beta < this.lowerBetaLimit) {
  44745. this.beta = this.lowerBetaLimit;
  44746. }
  44747. }
  44748. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  44749. if (this.allowUpsideDown && this.beta < -Math.PI) {
  44750. this.beta = this.beta + (2 * Math.PI);
  44751. }
  44752. }
  44753. else {
  44754. if (this.beta > this.upperBetaLimit) {
  44755. this.beta = this.upperBetaLimit;
  44756. }
  44757. }
  44758. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  44759. this.alpha = this.lowerAlphaLimit;
  44760. }
  44761. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  44762. this.alpha = this.upperAlphaLimit;
  44763. }
  44764. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  44765. this.radius = this.lowerRadiusLimit;
  44766. }
  44767. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  44768. this.radius = this.upperRadiusLimit;
  44769. }
  44770. };
  44771. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  44772. var radiusv3 = this.position.subtract(this._getTargetPosition());
  44773. this.radius = radiusv3.length();
  44774. if (this.radius === 0) {
  44775. this.radius = 0.0001; // Just to avoid division by zero
  44776. }
  44777. // Alpha
  44778. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  44779. if (radiusv3.z < 0) {
  44780. this.alpha = 2 * Math.PI - this.alpha;
  44781. }
  44782. // Beta
  44783. this.beta = Math.acos(radiusv3.y / this.radius);
  44784. this._checkLimits();
  44785. };
  44786. ArcRotateCamera.prototype.setPosition = function (position) {
  44787. if (this.position.equals(position)) {
  44788. return;
  44789. }
  44790. this.position.copyFrom(position);
  44791. this.rebuildAnglesAndRadius();
  44792. };
  44793. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  44794. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  44795. if (allowSamePosition === void 0) { allowSamePosition = false; }
  44796. if (target.getBoundingInfo) {
  44797. if (toBoundingCenter) {
  44798. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  44799. }
  44800. else {
  44801. this._targetBoundingCenter = null;
  44802. }
  44803. this._targetHost = target;
  44804. this._target = this._getTargetPosition();
  44805. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  44806. }
  44807. else {
  44808. var newTarget = target;
  44809. var currentTarget = this._getTargetPosition();
  44810. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  44811. return;
  44812. }
  44813. this._targetHost = null;
  44814. this._target = newTarget;
  44815. this._targetBoundingCenter = null;
  44816. this.onMeshTargetChangedObservable.notifyObservers(null);
  44817. }
  44818. this.rebuildAnglesAndRadius();
  44819. };
  44820. ArcRotateCamera.prototype._getViewMatrix = function () {
  44821. // Compute
  44822. var cosa = Math.cos(this.alpha);
  44823. var sina = Math.sin(this.alpha);
  44824. var cosb = Math.cos(this.beta);
  44825. var sinb = Math.sin(this.beta);
  44826. if (sinb === 0) {
  44827. sinb = 0.0001;
  44828. }
  44829. var target = this._getTargetPosition();
  44830. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  44831. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  44832. if (!this._collider) {
  44833. this._collider = new BABYLON.Collider();
  44834. }
  44835. this._collider._radius = this.collisionRadius;
  44836. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  44837. this._collisionTriggered = true;
  44838. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44839. }
  44840. else {
  44841. this.position.copyFrom(this._newPosition);
  44842. var up = this.upVector;
  44843. if (this.allowUpsideDown && sinb < 0) {
  44844. up = up.clone();
  44845. up = up.negate();
  44846. }
  44847. if (this.getScene().useRightHandedSystem) {
  44848. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  44849. }
  44850. else {
  44851. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  44852. }
  44853. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  44854. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  44855. }
  44856. this._currentTarget = target;
  44857. return this._viewMatrix;
  44858. };
  44859. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  44860. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44861. meshes = meshes || this.getScene().meshes;
  44862. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  44863. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  44864. this.radius = distance * this.zoomOnFactor;
  44865. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  44866. };
  44867. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  44868. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44869. var meshesOrMinMaxVector;
  44870. var distance;
  44871. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  44872. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  44873. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  44874. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  44875. }
  44876. else {
  44877. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  44878. meshesOrMinMaxVector = minMaxVectorAndDistance;
  44879. distance = minMaxVectorAndDistance.distance;
  44880. }
  44881. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  44882. if (!doNotUpdateMaxZ) {
  44883. this.maxZ = distance * 2;
  44884. }
  44885. };
  44886. /**
  44887. * @override
  44888. * Override Camera.createRigCamera
  44889. */
  44890. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  44891. var alphaShift = 0;
  44892. switch (this.cameraRigMode) {
  44893. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44894. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44895. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44896. case BABYLON.Camera.RIG_MODE_VR:
  44897. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  44898. break;
  44899. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44900. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  44901. break;
  44902. }
  44903. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  44904. rigCam._cameraRigParams = {};
  44905. return rigCam;
  44906. };
  44907. /**
  44908. * @override
  44909. * Override Camera._updateRigCameras
  44910. */
  44911. ArcRotateCamera.prototype._updateRigCameras = function () {
  44912. var camLeft = this._rigCameras[0];
  44913. var camRight = this._rigCameras[1];
  44914. camLeft.beta = camRight.beta = this.beta;
  44915. camLeft.radius = camRight.radius = this.radius;
  44916. switch (this.cameraRigMode) {
  44917. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44918. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44919. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44920. case BABYLON.Camera.RIG_MODE_VR:
  44921. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44922. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44923. break;
  44924. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44925. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44926. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44927. break;
  44928. }
  44929. _super.prototype._updateRigCameras.call(this);
  44930. };
  44931. ArcRotateCamera.prototype.dispose = function () {
  44932. this.inputs.clear();
  44933. _super.prototype.dispose.call(this);
  44934. };
  44935. ArcRotateCamera.prototype.getClassName = function () {
  44936. return "ArcRotateCamera";
  44937. };
  44938. __decorate([
  44939. BABYLON.serialize()
  44940. ], ArcRotateCamera.prototype, "alpha", void 0);
  44941. __decorate([
  44942. BABYLON.serialize()
  44943. ], ArcRotateCamera.prototype, "beta", void 0);
  44944. __decorate([
  44945. BABYLON.serialize()
  44946. ], ArcRotateCamera.prototype, "radius", void 0);
  44947. __decorate([
  44948. BABYLON.serializeAsVector3("target")
  44949. ], ArcRotateCamera.prototype, "_target", void 0);
  44950. __decorate([
  44951. BABYLON.serialize()
  44952. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  44953. __decorate([
  44954. BABYLON.serialize()
  44955. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  44956. __decorate([
  44957. BABYLON.serialize()
  44958. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  44959. __decorate([
  44960. BABYLON.serialize()
  44961. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  44962. __decorate([
  44963. BABYLON.serialize()
  44964. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  44965. __decorate([
  44966. BABYLON.serialize()
  44967. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  44968. __decorate([
  44969. BABYLON.serialize()
  44970. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  44971. __decorate([
  44972. BABYLON.serialize()
  44973. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  44974. __decorate([
  44975. BABYLON.serialize()
  44976. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  44977. __decorate([
  44978. BABYLON.serialize()
  44979. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  44980. __decorate([
  44981. BABYLON.serialize()
  44982. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  44983. __decorate([
  44984. BABYLON.serialize()
  44985. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  44986. __decorate([
  44987. BABYLON.serialize()
  44988. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  44989. __decorate([
  44990. BABYLON.serializeAsVector3()
  44991. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  44992. __decorate([
  44993. BABYLON.serialize()
  44994. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  44995. __decorate([
  44996. BABYLON.serialize()
  44997. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  44998. __decorate([
  44999. BABYLON.serialize()
  45000. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45001. return ArcRotateCamera;
  45002. }(BABYLON.TargetCamera));
  45003. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45004. })(BABYLON || (BABYLON = {}));
  45005. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45006. var BABYLON;
  45007. (function (BABYLON) {
  45008. /**
  45009. * The HemisphericLight simulates the ambient environment light,
  45010. * so the passed direction is the light reflection direction, not the incoming direction.
  45011. */
  45012. var HemisphericLight = /** @class */ (function (_super) {
  45013. __extends(HemisphericLight, _super);
  45014. /**
  45015. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45016. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45017. * The HemisphericLight can't cast shadows.
  45018. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45019. * @param name The friendly name of the light
  45020. * @param direction The direction of the light reflection
  45021. * @param scene The scene the light belongs to
  45022. */
  45023. function HemisphericLight(name, direction, scene) {
  45024. var _this = _super.call(this, name, scene) || this;
  45025. /**
  45026. * The groundColor is the light in the opposite direction to the one specified during creation.
  45027. * 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.
  45028. */
  45029. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45030. _this.direction = direction || BABYLON.Vector3.Up();
  45031. return _this;
  45032. }
  45033. HemisphericLight.prototype._buildUniformLayout = function () {
  45034. this._uniformBuffer.addUniform("vLightData", 4);
  45035. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45036. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45037. this._uniformBuffer.addUniform("vLightGround", 3);
  45038. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45039. this._uniformBuffer.addUniform("depthValues", 2);
  45040. this._uniformBuffer.create();
  45041. };
  45042. /**
  45043. * Returns the string "HemisphericLight".
  45044. * @return The class name
  45045. */
  45046. HemisphericLight.prototype.getClassName = function () {
  45047. return "HemisphericLight";
  45048. };
  45049. /**
  45050. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45051. * Returns the updated direction.
  45052. * @param target The target the direction should point to
  45053. * @return The computed direction
  45054. */
  45055. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45056. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45057. return this.direction;
  45058. };
  45059. /**
  45060. * Returns the shadow generator associated to the light.
  45061. * @returns Always null for hemispheric lights because it does not support shadows.
  45062. */
  45063. HemisphericLight.prototype.getShadowGenerator = function () {
  45064. return null;
  45065. };
  45066. /**
  45067. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45068. * @param effect The effect to update
  45069. * @param lightIndex The index of the light in the effect to update
  45070. * @returns The hemispheric light
  45071. */
  45072. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45073. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45074. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45075. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45076. return this;
  45077. };
  45078. /**
  45079. * @ignore internal use only.
  45080. */
  45081. HemisphericLight.prototype._getWorldMatrix = function () {
  45082. if (!this._worldMatrix) {
  45083. this._worldMatrix = BABYLON.Matrix.Identity();
  45084. }
  45085. return this._worldMatrix;
  45086. };
  45087. /**
  45088. * Returns the integer 3.
  45089. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45090. */
  45091. HemisphericLight.prototype.getTypeID = function () {
  45092. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45093. };
  45094. __decorate([
  45095. BABYLON.serializeAsColor3()
  45096. ], HemisphericLight.prototype, "groundColor", void 0);
  45097. __decorate([
  45098. BABYLON.serializeAsVector3()
  45099. ], HemisphericLight.prototype, "direction", void 0);
  45100. return HemisphericLight;
  45101. }(BABYLON.Light));
  45102. BABYLON.HemisphericLight = HemisphericLight;
  45103. })(BABYLON || (BABYLON = {}));
  45104. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45105. var BABYLON;
  45106. (function (BABYLON) {
  45107. /**
  45108. * Base implementation of @see IShadowLight
  45109. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45110. */
  45111. var ShadowLight = /** @class */ (function (_super) {
  45112. __extends(ShadowLight, _super);
  45113. function ShadowLight() {
  45114. var _this = _super !== null && _super.apply(this, arguments) || this;
  45115. _this._needProjectionMatrixCompute = true;
  45116. return _this;
  45117. }
  45118. ShadowLight.prototype._setPosition = function (value) {
  45119. this._position = value;
  45120. };
  45121. Object.defineProperty(ShadowLight.prototype, "position", {
  45122. /**
  45123. * Sets the position the shadow will be casted from. Also use as the light position for both
  45124. * point and spot lights.
  45125. */
  45126. get: function () {
  45127. return this._position;
  45128. },
  45129. /**
  45130. * Sets the position the shadow will be casted from. Also use as the light position for both
  45131. * point and spot lights.
  45132. */
  45133. set: function (value) {
  45134. this._setPosition(value);
  45135. },
  45136. enumerable: true,
  45137. configurable: true
  45138. });
  45139. ShadowLight.prototype._setDirection = function (value) {
  45140. this._direction = value;
  45141. };
  45142. Object.defineProperty(ShadowLight.prototype, "direction", {
  45143. /**
  45144. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45145. * Also use as the light direction on spot and directional lights.
  45146. */
  45147. get: function () {
  45148. return this._direction;
  45149. },
  45150. /**
  45151. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45152. * Also use as the light direction on spot and directional lights.
  45153. */
  45154. set: function (value) {
  45155. this._setDirection(value);
  45156. },
  45157. enumerable: true,
  45158. configurable: true
  45159. });
  45160. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45161. /**
  45162. * Gets the shadow projection clipping minimum z value.
  45163. */
  45164. get: function () {
  45165. return this._shadowMinZ;
  45166. },
  45167. /**
  45168. * Sets the shadow projection clipping minimum z value.
  45169. */
  45170. set: function (value) {
  45171. this._shadowMinZ = value;
  45172. this.forceProjectionMatrixCompute();
  45173. },
  45174. enumerable: true,
  45175. configurable: true
  45176. });
  45177. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  45178. /**
  45179. * Sets the shadow projection clipping maximum z value.
  45180. */
  45181. get: function () {
  45182. return this._shadowMaxZ;
  45183. },
  45184. /**
  45185. * Gets the shadow projection clipping maximum z value.
  45186. */
  45187. set: function (value) {
  45188. this._shadowMaxZ = value;
  45189. this.forceProjectionMatrixCompute();
  45190. },
  45191. enumerable: true,
  45192. configurable: true
  45193. });
  45194. /**
  45195. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  45196. * @returns true if the information has been computed, false if it does not need to (no parenting)
  45197. */
  45198. ShadowLight.prototype.computeTransformedInformation = function () {
  45199. if (this.parent && this.parent.getWorldMatrix) {
  45200. if (!this.transformedPosition) {
  45201. this.transformedPosition = BABYLON.Vector3.Zero();
  45202. }
  45203. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  45204. // In case the direction is present.
  45205. if (this.direction) {
  45206. if (!this.transformedDirection) {
  45207. this.transformedDirection = BABYLON.Vector3.Zero();
  45208. }
  45209. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  45210. }
  45211. return true;
  45212. }
  45213. return false;
  45214. };
  45215. /**
  45216. * Return the depth scale used for the shadow map.
  45217. * @returns the depth scale.
  45218. */
  45219. ShadowLight.prototype.getDepthScale = function () {
  45220. return 50.0;
  45221. };
  45222. /**
  45223. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  45224. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45225. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45226. */
  45227. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  45228. return this.transformedDirection ? this.transformedDirection : this.direction;
  45229. };
  45230. /**
  45231. * Returns the ShadowLight absolute position in the World.
  45232. * @returns the position vector in world space
  45233. */
  45234. ShadowLight.prototype.getAbsolutePosition = function () {
  45235. return this.transformedPosition ? this.transformedPosition : this.position;
  45236. };
  45237. /**
  45238. * Sets the ShadowLight direction toward the passed target.
  45239. * @param target The point tot target in local space
  45240. * @returns the updated ShadowLight direction
  45241. */
  45242. ShadowLight.prototype.setDirectionToTarget = function (target) {
  45243. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  45244. return this.direction;
  45245. };
  45246. /**
  45247. * Returns the light rotation in euler definition.
  45248. * @returns the x y z rotation in local space.
  45249. */
  45250. ShadowLight.prototype.getRotation = function () {
  45251. this.direction.normalize();
  45252. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  45253. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  45254. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  45255. };
  45256. /**
  45257. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  45258. * @returns true if a cube texture needs to be use
  45259. */
  45260. ShadowLight.prototype.needCube = function () {
  45261. return false;
  45262. };
  45263. /**
  45264. * Detects if the projection matrix requires to be recomputed this frame.
  45265. * @returns true if it requires to be recomputed otherwise, false.
  45266. */
  45267. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  45268. return this._needProjectionMatrixCompute;
  45269. };
  45270. /**
  45271. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  45272. */
  45273. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  45274. this._needProjectionMatrixCompute = true;
  45275. };
  45276. /**
  45277. * Get the world matrix of the sahdow lights.
  45278. * @ignore Internal Use Only
  45279. */
  45280. ShadowLight.prototype._getWorldMatrix = function () {
  45281. if (!this._worldMatrix) {
  45282. this._worldMatrix = BABYLON.Matrix.Identity();
  45283. }
  45284. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  45285. return this._worldMatrix;
  45286. };
  45287. /**
  45288. * Gets the minZ used for shadow according to both the scene and the light.
  45289. * @param activeCamera The camera we are returning the min for
  45290. * @returns the depth min z
  45291. */
  45292. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  45293. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  45294. };
  45295. /**
  45296. * Gets the maxZ used for shadow according to both the scene and the light.
  45297. * @param activeCamera The camera we are returning the max for
  45298. * @returns the depth max z
  45299. */
  45300. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  45301. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  45302. };
  45303. /**
  45304. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  45305. * @param matrix The materix to updated with the projection information
  45306. * @param viewMatrix The transform matrix of the light
  45307. * @param renderList The list of mesh to render in the map
  45308. * @returns The current light
  45309. */
  45310. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45311. if (this.customProjectionMatrixBuilder) {
  45312. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  45313. }
  45314. else {
  45315. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45316. }
  45317. return this;
  45318. };
  45319. __decorate([
  45320. BABYLON.serializeAsVector3()
  45321. ], ShadowLight.prototype, "position", null);
  45322. __decorate([
  45323. BABYLON.serializeAsVector3()
  45324. ], ShadowLight.prototype, "direction", null);
  45325. __decorate([
  45326. BABYLON.serialize()
  45327. ], ShadowLight.prototype, "shadowMinZ", null);
  45328. __decorate([
  45329. BABYLON.serialize()
  45330. ], ShadowLight.prototype, "shadowMaxZ", null);
  45331. return ShadowLight;
  45332. }(BABYLON.Light));
  45333. BABYLON.ShadowLight = ShadowLight;
  45334. })(BABYLON || (BABYLON = {}));
  45335. //# sourceMappingURL=babylon.shadowLight.js.map
  45336. var BABYLON;
  45337. (function (BABYLON) {
  45338. /**
  45339. * A point light is a light defined by an unique point in world space.
  45340. * The light is emitted in every direction from this point.
  45341. * A good example of a point light is a standard light bulb.
  45342. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45343. */
  45344. var PointLight = /** @class */ (function (_super) {
  45345. __extends(PointLight, _super);
  45346. /**
  45347. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  45348. * A PointLight emits the light in every direction.
  45349. * It can cast shadows.
  45350. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  45351. * ```javascript
  45352. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  45353. * ```
  45354. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45355. * @param name The light friendly name
  45356. * @param position The position of the point light in the scene
  45357. * @param scene The scene the lights belongs to
  45358. */
  45359. function PointLight(name, position, scene) {
  45360. var _this = _super.call(this, name, scene) || this;
  45361. _this._shadowAngle = Math.PI / 2;
  45362. _this.position = position;
  45363. return _this;
  45364. }
  45365. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  45366. /**
  45367. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45368. * This specifies what angle the shadow will use to be created.
  45369. *
  45370. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45371. */
  45372. get: function () {
  45373. return this._shadowAngle;
  45374. },
  45375. /**
  45376. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45377. * This specifies what angle the shadow will use to be created.
  45378. *
  45379. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45380. */
  45381. set: function (value) {
  45382. this._shadowAngle = value;
  45383. this.forceProjectionMatrixCompute();
  45384. },
  45385. enumerable: true,
  45386. configurable: true
  45387. });
  45388. Object.defineProperty(PointLight.prototype, "direction", {
  45389. /**
  45390. * Gets the direction if it has been set.
  45391. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45392. */
  45393. get: function () {
  45394. return this._direction;
  45395. },
  45396. /**
  45397. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45398. */
  45399. set: function (value) {
  45400. var previousNeedCube = this.needCube();
  45401. this._direction = value;
  45402. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  45403. this._shadowGenerator.recreateShadowMap();
  45404. }
  45405. },
  45406. enumerable: true,
  45407. configurable: true
  45408. });
  45409. /**
  45410. * Returns the string "PointLight"
  45411. * @returns the class name
  45412. */
  45413. PointLight.prototype.getClassName = function () {
  45414. return "PointLight";
  45415. };
  45416. /**
  45417. * Returns the integer 0.
  45418. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45419. */
  45420. PointLight.prototype.getTypeID = function () {
  45421. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  45422. };
  45423. /**
  45424. * Specifies wether or not the shadowmap should be a cube texture.
  45425. * @returns true if the shadowmap needs to be a cube texture.
  45426. */
  45427. PointLight.prototype.needCube = function () {
  45428. return !this.direction;
  45429. };
  45430. /**
  45431. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  45432. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45433. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45434. */
  45435. PointLight.prototype.getShadowDirection = function (faceIndex) {
  45436. if (this.direction) {
  45437. return _super.prototype.getShadowDirection.call(this, faceIndex);
  45438. }
  45439. else {
  45440. switch (faceIndex) {
  45441. case 0:
  45442. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  45443. case 1:
  45444. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  45445. case 2:
  45446. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  45447. case 3:
  45448. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  45449. case 4:
  45450. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  45451. case 5:
  45452. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  45453. }
  45454. }
  45455. return BABYLON.Vector3.Zero();
  45456. };
  45457. /**
  45458. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  45459. * - fov = PI / 2
  45460. * - aspect ratio : 1.0
  45461. * - z-near and far equal to the active camera minZ and maxZ.
  45462. * Returns the PointLight.
  45463. */
  45464. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45465. var activeCamera = this.getScene().activeCamera;
  45466. if (!activeCamera) {
  45467. return;
  45468. }
  45469. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45470. };
  45471. PointLight.prototype._buildUniformLayout = function () {
  45472. this._uniformBuffer.addUniform("vLightData", 4);
  45473. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45474. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45475. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45476. this._uniformBuffer.addUniform("depthValues", 2);
  45477. this._uniformBuffer.create();
  45478. };
  45479. /**
  45480. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  45481. * @param effect The effect to update
  45482. * @param lightIndex The index of the light in the effect to update
  45483. * @returns The point light
  45484. */
  45485. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  45486. if (this.computeTransformedInformation()) {
  45487. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  45488. return this;
  45489. }
  45490. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  45491. return this;
  45492. };
  45493. __decorate([
  45494. BABYLON.serialize()
  45495. ], PointLight.prototype, "shadowAngle", null);
  45496. return PointLight;
  45497. }(BABYLON.ShadowLight));
  45498. BABYLON.PointLight = PointLight;
  45499. })(BABYLON || (BABYLON = {}));
  45500. //# sourceMappingURL=babylon.pointLight.js.map
  45501. var BABYLON;
  45502. (function (BABYLON) {
  45503. /**
  45504. * A directional light is defined by a direction (what a surprise!).
  45505. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  45506. * 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.
  45507. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45508. */
  45509. var DirectionalLight = /** @class */ (function (_super) {
  45510. __extends(DirectionalLight, _super);
  45511. /**
  45512. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  45513. * The directional light is emitted from everywhere in the given direction.
  45514. * It can cast shawdows.
  45515. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45516. * @param name The friendly name of the light
  45517. * @param direction The direction of the light
  45518. * @param scene The scene the light belongs to
  45519. */
  45520. function DirectionalLight(name, direction, scene) {
  45521. var _this = _super.call(this, name, scene) || this;
  45522. _this._shadowFrustumSize = 0;
  45523. _this._shadowOrthoScale = 0.5;
  45524. /**
  45525. * Automatically compute the projection matrix to best fit (including all the casters)
  45526. * on each frame.
  45527. */
  45528. _this.autoUpdateExtends = true;
  45529. // Cache
  45530. _this._orthoLeft = Number.MAX_VALUE;
  45531. _this._orthoRight = Number.MIN_VALUE;
  45532. _this._orthoTop = Number.MIN_VALUE;
  45533. _this._orthoBottom = Number.MAX_VALUE;
  45534. _this.position = direction.scale(-1.0);
  45535. _this.direction = direction;
  45536. return _this;
  45537. }
  45538. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  45539. /**
  45540. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  45541. */
  45542. get: function () {
  45543. return this._shadowFrustumSize;
  45544. },
  45545. /**
  45546. * Specifies a fix frustum size for the shadow generation.
  45547. */
  45548. set: function (value) {
  45549. this._shadowFrustumSize = value;
  45550. this.forceProjectionMatrixCompute();
  45551. },
  45552. enumerable: true,
  45553. configurable: true
  45554. });
  45555. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  45556. /**
  45557. * Gets the shadow projection scale against the optimal computed one.
  45558. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45559. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45560. */
  45561. get: function () {
  45562. return this._shadowOrthoScale;
  45563. },
  45564. /**
  45565. * Sets the shadow projection scale against the optimal computed one.
  45566. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45567. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45568. */
  45569. set: function (value) {
  45570. this._shadowOrthoScale = value;
  45571. this.forceProjectionMatrixCompute();
  45572. },
  45573. enumerable: true,
  45574. configurable: true
  45575. });
  45576. /**
  45577. * Returns the string "DirectionalLight".
  45578. * @return The class name
  45579. */
  45580. DirectionalLight.prototype.getClassName = function () {
  45581. return "DirectionalLight";
  45582. };
  45583. /**
  45584. * Returns the integer 1.
  45585. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45586. */
  45587. DirectionalLight.prototype.getTypeID = function () {
  45588. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  45589. };
  45590. /**
  45591. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  45592. * Returns the DirectionalLight Shadow projection matrix.
  45593. */
  45594. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45595. if (this.shadowFrustumSize > 0) {
  45596. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  45597. }
  45598. else {
  45599. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45600. }
  45601. };
  45602. /**
  45603. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  45604. * Returns the DirectionalLight Shadow projection matrix.
  45605. */
  45606. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  45607. var activeCamera = this.getScene().activeCamera;
  45608. if (!activeCamera) {
  45609. return;
  45610. }
  45611. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  45612. };
  45613. /**
  45614. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  45615. * Returns the DirectionalLight Shadow projection matrix.
  45616. */
  45617. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45618. var activeCamera = this.getScene().activeCamera;
  45619. if (!activeCamera) {
  45620. return;
  45621. }
  45622. // Check extends
  45623. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  45624. var tempVector3 = BABYLON.Vector3.Zero();
  45625. this._orthoLeft = Number.MAX_VALUE;
  45626. this._orthoRight = Number.MIN_VALUE;
  45627. this._orthoTop = Number.MIN_VALUE;
  45628. this._orthoBottom = Number.MAX_VALUE;
  45629. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  45630. var mesh = renderList[meshIndex];
  45631. if (!mesh) {
  45632. continue;
  45633. }
  45634. var boundingInfo = mesh.getBoundingInfo();
  45635. var boundingBox = boundingInfo.boundingBox;
  45636. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  45637. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  45638. if (tempVector3.x < this._orthoLeft)
  45639. this._orthoLeft = tempVector3.x;
  45640. if (tempVector3.y < this._orthoBottom)
  45641. this._orthoBottom = tempVector3.y;
  45642. if (tempVector3.x > this._orthoRight)
  45643. this._orthoRight = tempVector3.x;
  45644. if (tempVector3.y > this._orthoTop)
  45645. this._orthoTop = tempVector3.y;
  45646. }
  45647. }
  45648. }
  45649. var xOffset = this._orthoRight - this._orthoLeft;
  45650. var yOffset = this._orthoTop - this._orthoBottom;
  45651. 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);
  45652. };
  45653. DirectionalLight.prototype._buildUniformLayout = function () {
  45654. this._uniformBuffer.addUniform("vLightData", 4);
  45655. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45656. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45657. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45658. this._uniformBuffer.addUniform("depthValues", 2);
  45659. this._uniformBuffer.create();
  45660. };
  45661. /**
  45662. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  45663. * @param effect The effect to update
  45664. * @param lightIndex The index of the light in the effect to update
  45665. * @returns The directional light
  45666. */
  45667. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  45668. if (this.computeTransformedInformation()) {
  45669. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  45670. return this;
  45671. }
  45672. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  45673. return this;
  45674. };
  45675. /**
  45676. * Gets the minZ used for shadow according to both the scene and the light.
  45677. *
  45678. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45679. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45680. * @param activeCamera The camera we are returning the min for
  45681. * @returns the depth min z
  45682. */
  45683. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  45684. return 1;
  45685. };
  45686. /**
  45687. * Gets the maxZ used for shadow according to both the scene and the light.
  45688. *
  45689. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45690. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45691. * @param activeCamera The camera we are returning the max for
  45692. * @returns the depth max z
  45693. */
  45694. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  45695. return 1;
  45696. };
  45697. __decorate([
  45698. BABYLON.serialize()
  45699. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  45700. __decorate([
  45701. BABYLON.serialize()
  45702. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  45703. __decorate([
  45704. BABYLON.serialize()
  45705. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  45706. return DirectionalLight;
  45707. }(BABYLON.ShadowLight));
  45708. BABYLON.DirectionalLight = DirectionalLight;
  45709. })(BABYLON || (BABYLON = {}));
  45710. //# sourceMappingURL=babylon.directionalLight.js.map
  45711. var BABYLON;
  45712. (function (BABYLON) {
  45713. /**
  45714. * A spot light is defined by a position, a direction, an angle, and an exponent.
  45715. * These values define a cone of light starting from the position, emitting toward the direction.
  45716. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  45717. * and the exponent defines the speed of the decay of the light with distance (reach).
  45718. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45719. */
  45720. var SpotLight = /** @class */ (function (_super) {
  45721. __extends(SpotLight, _super);
  45722. /**
  45723. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  45724. * It can cast shadows.
  45725. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45726. * @param name The light friendly name
  45727. * @param position The position of the spot light in the scene
  45728. * @param direction The direction of the light in the scene
  45729. * @param angle The cone angle of the light in Radians
  45730. * @param exponent The light decay speed with the distance from the emission spot
  45731. * @param scene The scene the lights belongs to
  45732. */
  45733. function SpotLight(name, position, direction, angle, exponent, scene) {
  45734. var _this = _super.call(this, name, scene) || this;
  45735. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  45736. _this._projectionTextureLightNear = 1e-6;
  45737. _this._projectionTextureLightFar = 1000.0;
  45738. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  45739. _this._projectionTextureViewLightDirty = true;
  45740. _this._projectionTextureProjectionLightDirty = true;
  45741. _this._projectionTextureDirty = true;
  45742. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  45743. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  45744. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  45745. _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);
  45746. _this.position = position;
  45747. _this.direction = direction;
  45748. _this.angle = angle;
  45749. _this.exponent = exponent;
  45750. return _this;
  45751. }
  45752. Object.defineProperty(SpotLight.prototype, "angle", {
  45753. /**
  45754. * Gets the cone angle of the spot light in Radians.
  45755. */
  45756. get: function () {
  45757. return this._angle;
  45758. },
  45759. /**
  45760. * Sets the cone angle of the spot light in Radians.
  45761. */
  45762. set: function (value) {
  45763. this._angle = value;
  45764. this._projectionTextureProjectionLightDirty = true;
  45765. this.forceProjectionMatrixCompute();
  45766. },
  45767. enumerable: true,
  45768. configurable: true
  45769. });
  45770. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  45771. /**
  45772. * Allows scaling the angle of the light for shadow generation only.
  45773. */
  45774. get: function () {
  45775. return this._shadowAngleScale;
  45776. },
  45777. /**
  45778. * Allows scaling the angle of the light for shadow generation only.
  45779. */
  45780. set: function (value) {
  45781. this._shadowAngleScale = value;
  45782. this.forceProjectionMatrixCompute();
  45783. },
  45784. enumerable: true,
  45785. configurable: true
  45786. });
  45787. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  45788. /**
  45789. * Allows reading the projecton texture
  45790. */
  45791. get: function () {
  45792. return this._projectionTextureMatrix;
  45793. },
  45794. enumerable: true,
  45795. configurable: true
  45796. });
  45797. ;
  45798. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  45799. /**
  45800. * Gets the near clip of the Spotlight for texture projection.
  45801. */
  45802. get: function () {
  45803. return this._projectionTextureLightNear;
  45804. },
  45805. /**
  45806. * Sets the near clip of the Spotlight for texture projection.
  45807. */
  45808. set: function (value) {
  45809. this._projectionTextureLightNear = value;
  45810. this._projectionTextureProjectionLightDirty = true;
  45811. },
  45812. enumerable: true,
  45813. configurable: true
  45814. });
  45815. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  45816. /**
  45817. * Gets the far clip of the Spotlight for texture projection.
  45818. */
  45819. get: function () {
  45820. return this._projectionTextureLightFar;
  45821. },
  45822. /**
  45823. * Sets the far clip of the Spotlight for texture projection.
  45824. */
  45825. set: function (value) {
  45826. this._projectionTextureLightFar = value;
  45827. this._projectionTextureProjectionLightDirty = true;
  45828. },
  45829. enumerable: true,
  45830. configurable: true
  45831. });
  45832. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  45833. /**
  45834. * Gets the Up vector of the Spotlight for texture projection.
  45835. */
  45836. get: function () {
  45837. return this._projectionTextureUpDirection;
  45838. },
  45839. /**
  45840. * Sets the Up vector of the Spotlight for texture projection.
  45841. */
  45842. set: function (value) {
  45843. this._projectionTextureUpDirection = value;
  45844. this._projectionTextureProjectionLightDirty = true;
  45845. },
  45846. enumerable: true,
  45847. configurable: true
  45848. });
  45849. ;
  45850. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  45851. /**
  45852. * Gets the projection texture of the light.
  45853. */
  45854. get: function () {
  45855. return this._projectionTexture;
  45856. },
  45857. /**
  45858. * Sets the projection texture of the light.
  45859. */
  45860. set: function (value) {
  45861. this._projectionTexture = value;
  45862. this._projectionTextureDirty = true;
  45863. },
  45864. enumerable: true,
  45865. configurable: true
  45866. });
  45867. /**
  45868. * Returns the string "SpotLight".
  45869. * @returns the class name
  45870. */
  45871. SpotLight.prototype.getClassName = function () {
  45872. return "SpotLight";
  45873. };
  45874. /**
  45875. * Returns the integer 2.
  45876. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45877. */
  45878. SpotLight.prototype.getTypeID = function () {
  45879. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  45880. };
  45881. /**
  45882. * Overrides the direction setter to recompute the projection texture view light Matrix.
  45883. */
  45884. SpotLight.prototype._setDirection = function (value) {
  45885. _super.prototype._setDirection.call(this, value);
  45886. this._projectionTextureViewLightDirty = true;
  45887. };
  45888. /**
  45889. * Overrides the position setter to recompute the projection texture view light Matrix.
  45890. */
  45891. SpotLight.prototype._setPosition = function (value) {
  45892. _super.prototype._setPosition.call(this, value);
  45893. this._projectionTextureViewLightDirty = true;
  45894. };
  45895. /**
  45896. * 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.
  45897. * Returns the SpotLight.
  45898. */
  45899. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45900. var activeCamera = this.getScene().activeCamera;
  45901. if (!activeCamera) {
  45902. return;
  45903. }
  45904. this._shadowAngleScale = this._shadowAngleScale || 1;
  45905. var angle = this._shadowAngleScale * this._angle;
  45906. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45907. };
  45908. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  45909. this._projectionTextureViewLightDirty = false;
  45910. this._projectionTextureDirty = true;
  45911. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  45912. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  45913. };
  45914. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  45915. this._projectionTextureProjectionLightDirty = false;
  45916. this._projectionTextureDirty = true;
  45917. var light_far = this.projectionTextureLightFar;
  45918. var light_near = this.projectionTextureLightNear;
  45919. var P = light_far / (light_far - light_near);
  45920. var Q = -P * light_near;
  45921. var S = 1.0 / Math.tan(this._angle / 2.0);
  45922. var A = 1.0;
  45923. 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);
  45924. };
  45925. /**
  45926. * Main function for light texture projection matrix computing.
  45927. */
  45928. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  45929. this._projectionTextureDirty = false;
  45930. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  45931. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  45932. };
  45933. SpotLight.prototype._buildUniformLayout = function () {
  45934. this._uniformBuffer.addUniform("vLightData", 4);
  45935. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45936. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45937. this._uniformBuffer.addUniform("vLightDirection", 3);
  45938. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45939. this._uniformBuffer.addUniform("depthValues", 2);
  45940. this._uniformBuffer.create();
  45941. };
  45942. /**
  45943. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  45944. * @param effect The effect to update
  45945. * @param lightIndex The index of the light in the effect to update
  45946. * @returns The spot light
  45947. */
  45948. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  45949. var normalizeDirection;
  45950. if (this.computeTransformedInformation()) {
  45951. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  45952. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  45953. }
  45954. else {
  45955. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  45956. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45957. }
  45958. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  45959. if (this.projectionTexture && this.projectionTexture.isReady()) {
  45960. if (this._projectionTextureViewLightDirty) {
  45961. this._computeProjectionTextureViewLightMatrix();
  45962. }
  45963. if (this._projectionTextureProjectionLightDirty) {
  45964. this._computeProjectionTextureProjectionLightMatrix();
  45965. }
  45966. if (this._projectionTextureDirty) {
  45967. this._computeProjectionTextureMatrix();
  45968. }
  45969. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  45970. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  45971. }
  45972. return this;
  45973. };
  45974. /**
  45975. * Disposes the light and the associated resources.
  45976. */
  45977. SpotLight.prototype.dispose = function () {
  45978. _super.prototype.dispose.call(this);
  45979. if (this._projectionTexture) {
  45980. this._projectionTexture.dispose();
  45981. }
  45982. };
  45983. __decorate([
  45984. BABYLON.serialize()
  45985. ], SpotLight.prototype, "angle", null);
  45986. __decorate([
  45987. BABYLON.serialize()
  45988. ], SpotLight.prototype, "shadowAngleScale", null);
  45989. __decorate([
  45990. BABYLON.serialize()
  45991. ], SpotLight.prototype, "exponent", void 0);
  45992. __decorate([
  45993. BABYLON.serialize()
  45994. ], SpotLight.prototype, "projectionTextureLightNear", null);
  45995. __decorate([
  45996. BABYLON.serialize()
  45997. ], SpotLight.prototype, "projectionTextureLightFar", null);
  45998. __decorate([
  45999. BABYLON.serialize()
  46000. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46001. __decorate([
  46002. BABYLON.serializeAsTexture("projectedLightTexture")
  46003. ], SpotLight.prototype, "_projectionTexture", void 0);
  46004. return SpotLight;
  46005. }(BABYLON.ShadowLight));
  46006. BABYLON.SpotLight = SpotLight;
  46007. })(BABYLON || (BABYLON = {}));
  46008. //# sourceMappingURL=babylon.spotLight.js.map
  46009. var BABYLON;
  46010. (function (BABYLON) {
  46011. var AnimationRange = /** @class */ (function () {
  46012. function AnimationRange(name, from, to) {
  46013. this.name = name;
  46014. this.from = from;
  46015. this.to = to;
  46016. }
  46017. AnimationRange.prototype.clone = function () {
  46018. return new AnimationRange(this.name, this.from, this.to);
  46019. };
  46020. return AnimationRange;
  46021. }());
  46022. BABYLON.AnimationRange = AnimationRange;
  46023. /**
  46024. * Composed of a frame, and an action function
  46025. */
  46026. var AnimationEvent = /** @class */ (function () {
  46027. function AnimationEvent(frame, action, onlyOnce) {
  46028. this.frame = frame;
  46029. this.action = action;
  46030. this.onlyOnce = onlyOnce;
  46031. this.isDone = false;
  46032. }
  46033. return AnimationEvent;
  46034. }());
  46035. BABYLON.AnimationEvent = AnimationEvent;
  46036. var PathCursor = /** @class */ (function () {
  46037. function PathCursor(path) {
  46038. this.path = path;
  46039. this._onchange = new Array();
  46040. this.value = 0;
  46041. this.animations = new Array();
  46042. }
  46043. PathCursor.prototype.getPoint = function () {
  46044. var point = this.path.getPointAtLengthPosition(this.value);
  46045. return new BABYLON.Vector3(point.x, 0, point.y);
  46046. };
  46047. PathCursor.prototype.moveAhead = function (step) {
  46048. if (step === void 0) { step = 0.002; }
  46049. this.move(step);
  46050. return this;
  46051. };
  46052. PathCursor.prototype.moveBack = function (step) {
  46053. if (step === void 0) { step = 0.002; }
  46054. this.move(-step);
  46055. return this;
  46056. };
  46057. PathCursor.prototype.move = function (step) {
  46058. if (Math.abs(step) > 1) {
  46059. throw "step size should be less than 1.";
  46060. }
  46061. this.value += step;
  46062. this.ensureLimits();
  46063. this.raiseOnChange();
  46064. return this;
  46065. };
  46066. PathCursor.prototype.ensureLimits = function () {
  46067. while (this.value > 1) {
  46068. this.value -= 1;
  46069. }
  46070. while (this.value < 0) {
  46071. this.value += 1;
  46072. }
  46073. return this;
  46074. };
  46075. // used by animation engine
  46076. PathCursor.prototype.raiseOnChange = function () {
  46077. var _this = this;
  46078. this._onchange.forEach(function (f) { return f(_this); });
  46079. return this;
  46080. };
  46081. PathCursor.prototype.onchange = function (f) {
  46082. this._onchange.push(f);
  46083. return this;
  46084. };
  46085. return PathCursor;
  46086. }());
  46087. BABYLON.PathCursor = PathCursor;
  46088. var AnimationKeyInterpolation;
  46089. (function (AnimationKeyInterpolation) {
  46090. /**
  46091. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46092. */
  46093. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46094. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46095. var Animation = /** @class */ (function () {
  46096. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46097. this.name = name;
  46098. this.targetProperty = targetProperty;
  46099. this.framePerSecond = framePerSecond;
  46100. this.dataType = dataType;
  46101. this.loopMode = loopMode;
  46102. this.enableBlending = enableBlending;
  46103. this._runtimeAnimations = new Array();
  46104. // The set of event that will be linked to this animation
  46105. this._events = new Array();
  46106. this.blendingSpeed = 0.01;
  46107. this._ranges = {};
  46108. this.targetPropertyPath = targetProperty.split(".");
  46109. this.dataType = dataType;
  46110. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46111. }
  46112. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46113. var dataType = undefined;
  46114. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46115. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46116. }
  46117. else if (from instanceof BABYLON.Quaternion) {
  46118. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46119. }
  46120. else if (from instanceof BABYLON.Vector3) {
  46121. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46122. }
  46123. else if (from instanceof BABYLON.Vector2) {
  46124. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46125. }
  46126. else if (from instanceof BABYLON.Color3) {
  46127. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46128. }
  46129. else if (from instanceof BABYLON.Size) {
  46130. dataType = Animation.ANIMATIONTYPE_SIZE;
  46131. }
  46132. if (dataType == undefined) {
  46133. return null;
  46134. }
  46135. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46136. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46137. animation.setKeys(keys);
  46138. if (easingFunction !== undefined) {
  46139. animation.setEasingFunction(easingFunction);
  46140. }
  46141. return animation;
  46142. };
  46143. /**
  46144. * Sets up an animation.
  46145. * @param property the property to animate
  46146. * @param animationType the animation type to apply
  46147. * @param easingFunction the easing function used in the animation
  46148. * @returns The created animation
  46149. */
  46150. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  46151. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  46152. animation.setEasingFunction(easingFunction);
  46153. return animation;
  46154. };
  46155. /**
  46156. * Create and start an animation on a node
  46157. * @param {string} name defines the name of the global animation that will be run on all nodes
  46158. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46159. * @param {string} targetProperty defines property to animate
  46160. * @param {number} framePerSecond defines the number of frame per second yo use
  46161. * @param {number} totalFrame defines the number of frames in total
  46162. * @param {any} from defines the initial value
  46163. * @param {any} to defines the final value
  46164. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46165. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46166. * @param onAnimationEnd defines the callback to call when animation end
  46167. * @returns the animatable created for this animation
  46168. */
  46169. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46170. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46171. if (!animation) {
  46172. return null;
  46173. }
  46174. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46175. };
  46176. /**
  46177. * Create and start an animation on a node and its descendants
  46178. * @param {string} name defines the name of the global animation that will be run on all nodes
  46179. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46180. * @param {boolean} 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.
  46181. * @param {string} targetProperty defines property to animate
  46182. * @param {number} framePerSecond defines the number of frame per second yo use
  46183. * @param {number} totalFrame defines the number of frames in total
  46184. * @param {any} from defines the initial value
  46185. * @param {any} to defines the final value
  46186. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46187. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46188. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  46189. * @returns the list of animatables created for all nodes
  46190. * @example https://www.babylonjs-playground.com/#MH0VLI
  46191. */
  46192. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46193. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46194. if (!animation) {
  46195. return null;
  46196. }
  46197. var scene = node.getScene();
  46198. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46199. };
  46200. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46201. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46202. if (!animation) {
  46203. return null;
  46204. }
  46205. node.animations.push(animation);
  46206. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46207. };
  46208. /**
  46209. * Transition property of the Camera to the target Value.
  46210. * @param property The property to transition
  46211. * @param targetValue The target Value of the property
  46212. * @param host The object where the property to animate belongs
  46213. * @param scene Scene used to run the animation
  46214. * @param frameRate Framerate (in frame/s) to use
  46215. * @param transition The transition type we want to use
  46216. * @param duration The duration of the animation, in milliseconds
  46217. * @param onAnimationEnd Call back trigger at the end of the animation.
  46218. */
  46219. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  46220. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  46221. if (duration <= 0) {
  46222. host[property] = targetValue;
  46223. if (onAnimationEnd) {
  46224. onAnimationEnd();
  46225. }
  46226. return null;
  46227. }
  46228. var endFrame = frameRate * (duration / 1000);
  46229. transition.setKeys([{
  46230. frame: 0,
  46231. value: host[property].clone ? host[property].clone() : host[property]
  46232. },
  46233. {
  46234. frame: endFrame,
  46235. value: targetValue
  46236. }]);
  46237. if (!host.animations) {
  46238. host.animations = [];
  46239. }
  46240. host.animations.push(transition);
  46241. var animation = scene.beginAnimation(host, 0, endFrame, false);
  46242. animation.onAnimationEnd = onAnimationEnd;
  46243. return animation;
  46244. };
  46245. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  46246. /**
  46247. * Return the array of runtime animations currently using this animation
  46248. */
  46249. get: function () {
  46250. return this._runtimeAnimations;
  46251. },
  46252. enumerable: true,
  46253. configurable: true
  46254. });
  46255. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  46256. get: function () {
  46257. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  46258. var runtimeAnimation = _a[_i];
  46259. if (!runtimeAnimation.isStopped) {
  46260. return true;
  46261. }
  46262. }
  46263. return false;
  46264. },
  46265. enumerable: true,
  46266. configurable: true
  46267. });
  46268. // Methods
  46269. /**
  46270. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  46271. */
  46272. Animation.prototype.toString = function (fullDetails) {
  46273. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  46274. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  46275. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  46276. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  46277. if (fullDetails) {
  46278. ret += ", Ranges: {";
  46279. var first = true;
  46280. for (var name in this._ranges) {
  46281. if (first) {
  46282. ret += ", ";
  46283. first = false;
  46284. }
  46285. ret += name;
  46286. }
  46287. ret += "}";
  46288. }
  46289. return ret;
  46290. };
  46291. /**
  46292. * Add an event to this animation.
  46293. */
  46294. Animation.prototype.addEvent = function (event) {
  46295. this._events.push(event);
  46296. };
  46297. /**
  46298. * Remove all events found at the given frame
  46299. * @param frame
  46300. */
  46301. Animation.prototype.removeEvents = function (frame) {
  46302. for (var index = 0; index < this._events.length; index++) {
  46303. if (this._events[index].frame === frame) {
  46304. this._events.splice(index, 1);
  46305. index--;
  46306. }
  46307. }
  46308. };
  46309. Animation.prototype.getEvents = function () {
  46310. return this._events;
  46311. };
  46312. Animation.prototype.createRange = function (name, from, to) {
  46313. // check name not already in use; could happen for bones after serialized
  46314. if (!this._ranges[name]) {
  46315. this._ranges[name] = new AnimationRange(name, from, to);
  46316. }
  46317. };
  46318. Animation.prototype.deleteRange = function (name, deleteFrames) {
  46319. if (deleteFrames === void 0) { deleteFrames = true; }
  46320. var range = this._ranges[name];
  46321. if (!range) {
  46322. return;
  46323. }
  46324. if (deleteFrames) {
  46325. var from = range.from;
  46326. var to = range.to;
  46327. // this loop MUST go high to low for multiple splices to work
  46328. for (var key = this._keys.length - 1; key >= 0; key--) {
  46329. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  46330. this._keys.splice(key, 1);
  46331. }
  46332. }
  46333. }
  46334. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  46335. };
  46336. Animation.prototype.getRange = function (name) {
  46337. return this._ranges[name];
  46338. };
  46339. Animation.prototype.getKeys = function () {
  46340. return this._keys;
  46341. };
  46342. Animation.prototype.getHighestFrame = function () {
  46343. var ret = 0;
  46344. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  46345. if (ret < this._keys[key].frame) {
  46346. ret = this._keys[key].frame;
  46347. }
  46348. }
  46349. return ret;
  46350. };
  46351. Animation.prototype.getEasingFunction = function () {
  46352. return this._easingFunction;
  46353. };
  46354. Animation.prototype.setEasingFunction = function (easingFunction) {
  46355. this._easingFunction = easingFunction;
  46356. };
  46357. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  46358. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  46359. };
  46360. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46361. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46362. };
  46363. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  46364. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  46365. };
  46366. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46367. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  46368. };
  46369. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  46370. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  46371. };
  46372. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46373. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46374. };
  46375. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  46376. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  46377. };
  46378. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46379. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46380. };
  46381. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  46382. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  46383. };
  46384. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  46385. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  46386. };
  46387. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  46388. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  46389. };
  46390. Animation.prototype.clone = function () {
  46391. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  46392. clone.enableBlending = this.enableBlending;
  46393. clone.blendingSpeed = this.blendingSpeed;
  46394. if (this._keys) {
  46395. clone.setKeys(this._keys);
  46396. }
  46397. if (this._ranges) {
  46398. clone._ranges = {};
  46399. for (var name in this._ranges) {
  46400. var range = this._ranges[name];
  46401. if (!range) {
  46402. continue;
  46403. }
  46404. clone._ranges[name] = range.clone();
  46405. }
  46406. }
  46407. return clone;
  46408. };
  46409. Animation.prototype.setKeys = function (values) {
  46410. this._keys = values.slice(0);
  46411. };
  46412. Animation.prototype.serialize = function () {
  46413. var serializationObject = {};
  46414. serializationObject.name = this.name;
  46415. serializationObject.property = this.targetProperty;
  46416. serializationObject.framePerSecond = this.framePerSecond;
  46417. serializationObject.dataType = this.dataType;
  46418. serializationObject.loopBehavior = this.loopMode;
  46419. serializationObject.enableBlending = this.enableBlending;
  46420. serializationObject.blendingSpeed = this.blendingSpeed;
  46421. var dataType = this.dataType;
  46422. serializationObject.keys = [];
  46423. var keys = this.getKeys();
  46424. for (var index = 0; index < keys.length; index++) {
  46425. var animationKey = keys[index];
  46426. var key = {};
  46427. key.frame = animationKey.frame;
  46428. switch (dataType) {
  46429. case Animation.ANIMATIONTYPE_FLOAT:
  46430. key.values = [animationKey.value];
  46431. break;
  46432. case Animation.ANIMATIONTYPE_QUATERNION:
  46433. case Animation.ANIMATIONTYPE_MATRIX:
  46434. case Animation.ANIMATIONTYPE_VECTOR3:
  46435. case Animation.ANIMATIONTYPE_COLOR3:
  46436. key.values = animationKey.value.asArray();
  46437. break;
  46438. }
  46439. serializationObject.keys.push(key);
  46440. }
  46441. serializationObject.ranges = [];
  46442. for (var name in this._ranges) {
  46443. var source = this._ranges[name];
  46444. if (!source) {
  46445. continue;
  46446. }
  46447. var range = {};
  46448. range.name = name;
  46449. range.from = source.from;
  46450. range.to = source.to;
  46451. serializationObject.ranges.push(range);
  46452. }
  46453. return serializationObject;
  46454. };
  46455. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  46456. get: function () {
  46457. return Animation._ANIMATIONTYPE_FLOAT;
  46458. },
  46459. enumerable: true,
  46460. configurable: true
  46461. });
  46462. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  46463. get: function () {
  46464. return Animation._ANIMATIONTYPE_VECTOR3;
  46465. },
  46466. enumerable: true,
  46467. configurable: true
  46468. });
  46469. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  46470. get: function () {
  46471. return Animation._ANIMATIONTYPE_VECTOR2;
  46472. },
  46473. enumerable: true,
  46474. configurable: true
  46475. });
  46476. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  46477. get: function () {
  46478. return Animation._ANIMATIONTYPE_SIZE;
  46479. },
  46480. enumerable: true,
  46481. configurable: true
  46482. });
  46483. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  46484. get: function () {
  46485. return Animation._ANIMATIONTYPE_QUATERNION;
  46486. },
  46487. enumerable: true,
  46488. configurable: true
  46489. });
  46490. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  46491. get: function () {
  46492. return Animation._ANIMATIONTYPE_MATRIX;
  46493. },
  46494. enumerable: true,
  46495. configurable: true
  46496. });
  46497. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  46498. get: function () {
  46499. return Animation._ANIMATIONTYPE_COLOR3;
  46500. },
  46501. enumerable: true,
  46502. configurable: true
  46503. });
  46504. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  46505. get: function () {
  46506. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  46507. },
  46508. enumerable: true,
  46509. configurable: true
  46510. });
  46511. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  46512. get: function () {
  46513. return Animation._ANIMATIONLOOPMODE_CYCLE;
  46514. },
  46515. enumerable: true,
  46516. configurable: true
  46517. });
  46518. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  46519. get: function () {
  46520. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  46521. },
  46522. enumerable: true,
  46523. configurable: true
  46524. });
  46525. Animation.Parse = function (parsedAnimation) {
  46526. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  46527. var dataType = parsedAnimation.dataType;
  46528. var keys = [];
  46529. var data;
  46530. var index;
  46531. if (parsedAnimation.enableBlending) {
  46532. animation.enableBlending = parsedAnimation.enableBlending;
  46533. }
  46534. if (parsedAnimation.blendingSpeed) {
  46535. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  46536. }
  46537. for (index = 0; index < parsedAnimation.keys.length; index++) {
  46538. var key = parsedAnimation.keys[index];
  46539. var inTangent;
  46540. var outTangent;
  46541. switch (dataType) {
  46542. case Animation.ANIMATIONTYPE_FLOAT:
  46543. data = key.values[0];
  46544. if (key.values.length >= 1) {
  46545. inTangent = key.values[1];
  46546. }
  46547. if (key.values.length >= 2) {
  46548. outTangent = key.values[2];
  46549. }
  46550. break;
  46551. case Animation.ANIMATIONTYPE_QUATERNION:
  46552. data = BABYLON.Quaternion.FromArray(key.values);
  46553. if (key.values.length >= 8) {
  46554. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  46555. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  46556. inTangent = _inTangent;
  46557. }
  46558. }
  46559. if (key.values.length >= 12) {
  46560. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  46561. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  46562. outTangent = _outTangent;
  46563. }
  46564. }
  46565. break;
  46566. case Animation.ANIMATIONTYPE_MATRIX:
  46567. data = BABYLON.Matrix.FromArray(key.values);
  46568. break;
  46569. case Animation.ANIMATIONTYPE_COLOR3:
  46570. data = BABYLON.Color3.FromArray(key.values);
  46571. break;
  46572. case Animation.ANIMATIONTYPE_VECTOR3:
  46573. default:
  46574. data = BABYLON.Vector3.FromArray(key.values);
  46575. break;
  46576. }
  46577. var keyData = {};
  46578. keyData.frame = key.frame;
  46579. keyData.value = data;
  46580. if (inTangent != undefined) {
  46581. keyData.inTangent = inTangent;
  46582. }
  46583. if (outTangent != undefined) {
  46584. keyData.outTangent = outTangent;
  46585. }
  46586. keys.push(keyData);
  46587. }
  46588. animation.setKeys(keys);
  46589. if (parsedAnimation.ranges) {
  46590. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  46591. data = parsedAnimation.ranges[index];
  46592. animation.createRange(data.name, data.from, data.to);
  46593. }
  46594. }
  46595. return animation;
  46596. };
  46597. Animation.AppendSerializedAnimations = function (source, destination) {
  46598. if (source.animations) {
  46599. destination.animations = [];
  46600. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  46601. var animation = source.animations[animationIndex];
  46602. destination.animations.push(animation.serialize());
  46603. }
  46604. }
  46605. };
  46606. Animation.AllowMatricesInterpolation = false;
  46607. // Statics
  46608. Animation._ANIMATIONTYPE_FLOAT = 0;
  46609. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  46610. Animation._ANIMATIONTYPE_QUATERNION = 2;
  46611. Animation._ANIMATIONTYPE_MATRIX = 3;
  46612. Animation._ANIMATIONTYPE_COLOR3 = 4;
  46613. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  46614. Animation._ANIMATIONTYPE_SIZE = 6;
  46615. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  46616. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  46617. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  46618. return Animation;
  46619. }());
  46620. BABYLON.Animation = Animation;
  46621. })(BABYLON || (BABYLON = {}));
  46622. //# sourceMappingURL=babylon.animation.js.map
  46623. var BABYLON;
  46624. (function (BABYLON) {
  46625. /**
  46626. * This class defines the direct association between an animation and a target
  46627. */
  46628. var TargetedAnimation = /** @class */ (function () {
  46629. function TargetedAnimation() {
  46630. }
  46631. return TargetedAnimation;
  46632. }());
  46633. BABYLON.TargetedAnimation = TargetedAnimation;
  46634. /**
  46635. * Use this class to create coordinated animations on multiple targets
  46636. */
  46637. var AnimationGroup = /** @class */ (function () {
  46638. function AnimationGroup(name, scene) {
  46639. if (scene === void 0) { scene = null; }
  46640. this.name = name;
  46641. this._targetedAnimations = new Array();
  46642. this._animatables = new Array();
  46643. this._from = Number.MAX_VALUE;
  46644. this._to = -Number.MAX_VALUE;
  46645. this._speedRatio = 1;
  46646. this.onAnimationEndObservable = new BABYLON.Observable();
  46647. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46648. this._scene.animationGroups.push(this);
  46649. }
  46650. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  46651. /**
  46652. * Define if the animations are started
  46653. */
  46654. get: function () {
  46655. return this._isStarted;
  46656. },
  46657. enumerable: true,
  46658. configurable: true
  46659. });
  46660. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  46661. /**
  46662. * Gets or sets the speed ratio to use for all animations
  46663. */
  46664. get: function () {
  46665. return this._speedRatio;
  46666. },
  46667. /**
  46668. * Gets or sets the speed ratio to use for all animations
  46669. */
  46670. set: function (value) {
  46671. if (this._speedRatio === value) {
  46672. return;
  46673. }
  46674. this._speedRatio = value;
  46675. for (var index = 0; index < this._animatables.length; index++) {
  46676. var animatable = this._animatables[index];
  46677. animatable.speedRatio = this._speedRatio;
  46678. }
  46679. },
  46680. enumerable: true,
  46681. configurable: true
  46682. });
  46683. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  46684. /**
  46685. * Gets the targeted animations for this animation group
  46686. */
  46687. get: function () {
  46688. return this._targetedAnimations;
  46689. },
  46690. enumerable: true,
  46691. configurable: true
  46692. });
  46693. /**
  46694. * Add an animation (with its target) in the group
  46695. * @param animation defines the animation we want to add
  46696. * @param target defines the target of the animation
  46697. * @returns the {BABYLON.TargetedAnimation} object
  46698. */
  46699. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  46700. var targetedAnimation = {
  46701. animation: animation,
  46702. target: target
  46703. };
  46704. var keys = animation.getKeys();
  46705. if (this._from > keys[0].frame) {
  46706. this._from = keys[0].frame;
  46707. }
  46708. if (this._to < keys[keys.length - 1].frame) {
  46709. this._to = keys[keys.length - 1].frame;
  46710. }
  46711. this._targetedAnimations.push(targetedAnimation);
  46712. return targetedAnimation;
  46713. };
  46714. /**
  46715. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  46716. * It can add constant keys at begin or end
  46717. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  46718. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  46719. */
  46720. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  46721. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  46722. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  46723. beginFrame = Math.max(beginFrame, this._from);
  46724. endFrame = Math.min(endFrame, this._to);
  46725. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46726. var targetedAnimation = this._targetedAnimations[index];
  46727. var keys = targetedAnimation.animation.getKeys();
  46728. var startKey = keys[0];
  46729. var endKey = keys[keys.length - 1];
  46730. if (startKey.frame > beginFrame) {
  46731. var newKey = {
  46732. frame: beginFrame,
  46733. value: startKey.value,
  46734. inTangent: startKey.inTangent,
  46735. outTangent: startKey.outTangent,
  46736. interpolation: startKey.interpolation
  46737. };
  46738. keys.splice(0, 0, newKey);
  46739. }
  46740. if (endKey.frame < endFrame) {
  46741. var newKey = {
  46742. frame: endFrame,
  46743. value: endKey.value,
  46744. inTangent: endKey.outTangent,
  46745. outTangent: endKey.outTangent,
  46746. interpolation: endKey.interpolation
  46747. };
  46748. keys.push(newKey);
  46749. }
  46750. }
  46751. return this;
  46752. };
  46753. /**
  46754. * Start all animations on given targets
  46755. * @param loop defines if animations must loop
  46756. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  46757. */
  46758. AnimationGroup.prototype.start = function (loop, speedRatio) {
  46759. var _this = this;
  46760. if (loop === void 0) { loop = false; }
  46761. if (speedRatio === void 0) { speedRatio = 1; }
  46762. if (this._isStarted || this._targetedAnimations.length === 0) {
  46763. return this;
  46764. }
  46765. var _loop_1 = function () {
  46766. var targetedAnimation = this_1._targetedAnimations[index];
  46767. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  46768. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  46769. }));
  46770. };
  46771. var this_1 = this;
  46772. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46773. _loop_1();
  46774. }
  46775. this._speedRatio = speedRatio;
  46776. this._isStarted = true;
  46777. return this;
  46778. };
  46779. /**
  46780. * Pause all animations
  46781. */
  46782. AnimationGroup.prototype.pause = function () {
  46783. if (!this._isStarted) {
  46784. return this;
  46785. }
  46786. for (var index = 0; index < this._animatables.length; index++) {
  46787. var animatable = this._animatables[index];
  46788. animatable.pause();
  46789. }
  46790. return this;
  46791. };
  46792. /**
  46793. * Play all animations to initial state
  46794. * This function will start() the animations if they were not started or will restart() them if they were paused
  46795. * @param loop defines if animations must loop
  46796. */
  46797. AnimationGroup.prototype.play = function (loop) {
  46798. if (this.isStarted) {
  46799. if (loop !== undefined) {
  46800. for (var index = 0; index < this._animatables.length; index++) {
  46801. var animatable = this._animatables[index];
  46802. animatable.loopAnimation = loop;
  46803. }
  46804. }
  46805. this.restart();
  46806. }
  46807. else {
  46808. this.start(loop, this._speedRatio);
  46809. }
  46810. return this;
  46811. };
  46812. /**
  46813. * Reset all animations to initial state
  46814. */
  46815. AnimationGroup.prototype.reset = function () {
  46816. if (!this._isStarted) {
  46817. return this;
  46818. }
  46819. for (var index = 0; index < this._animatables.length; index++) {
  46820. var animatable = this._animatables[index];
  46821. animatable.reset();
  46822. }
  46823. return this;
  46824. };
  46825. /**
  46826. * Restart animations from key 0
  46827. */
  46828. AnimationGroup.prototype.restart = function () {
  46829. if (!this._isStarted) {
  46830. return this;
  46831. }
  46832. for (var index = 0; index < this._animatables.length; index++) {
  46833. var animatable = this._animatables[index];
  46834. animatable.restart();
  46835. }
  46836. return this;
  46837. };
  46838. /**
  46839. * Stop all animations
  46840. */
  46841. AnimationGroup.prototype.stop = function () {
  46842. if (!this._isStarted) {
  46843. return this;
  46844. }
  46845. for (var index = 0; index < this._animatables.length; index++) {
  46846. var animatable = this._animatables[index];
  46847. animatable.stop();
  46848. }
  46849. this._isStarted = false;
  46850. return this;
  46851. };
  46852. /**
  46853. * Dispose all associated resources
  46854. */
  46855. AnimationGroup.prototype.dispose = function () {
  46856. this._targetedAnimations = [];
  46857. this._animatables = [];
  46858. var index = this._scene.animationGroups.indexOf(this);
  46859. if (index > -1) {
  46860. this._scene.animationGroups.splice(index, 1);
  46861. }
  46862. };
  46863. return AnimationGroup;
  46864. }());
  46865. BABYLON.AnimationGroup = AnimationGroup;
  46866. })(BABYLON || (BABYLON = {}));
  46867. //# sourceMappingURL=babylon.animationGroup.js.map
  46868. var BABYLON;
  46869. (function (BABYLON) {
  46870. var RuntimeAnimation = /** @class */ (function () {
  46871. function RuntimeAnimation(target, animation) {
  46872. this._offsetsCache = {};
  46873. this._highLimitsCache = {};
  46874. this._stopped = false;
  46875. this._blendingFactor = 0;
  46876. this._ratioOffset = 0;
  46877. this._animation = animation;
  46878. this._target = target;
  46879. animation._runtimeAnimations.push(this);
  46880. }
  46881. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  46882. get: function () {
  46883. return this._animation;
  46884. },
  46885. enumerable: true,
  46886. configurable: true
  46887. });
  46888. RuntimeAnimation.prototype.reset = function () {
  46889. this._offsetsCache = {};
  46890. this._highLimitsCache = {};
  46891. this.currentFrame = 0;
  46892. this._blendingFactor = 0;
  46893. this._originalBlendValue = null;
  46894. };
  46895. RuntimeAnimation.prototype.isStopped = function () {
  46896. return this._stopped;
  46897. };
  46898. RuntimeAnimation.prototype.dispose = function () {
  46899. var index = this._animation.runtimeAnimations.indexOf(this);
  46900. if (index > -1) {
  46901. this._animation.runtimeAnimations.splice(index, 1);
  46902. }
  46903. };
  46904. RuntimeAnimation.prototype._getKeyValue = function (value) {
  46905. if (typeof value === "function") {
  46906. return value();
  46907. }
  46908. return value;
  46909. };
  46910. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  46911. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  46912. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  46913. }
  46914. this.currentFrame = currentFrame;
  46915. var keys = this._animation.getKeys();
  46916. // Try to get a hash to find the right key
  46917. 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));
  46918. if (keys[startKeyIndex].frame >= currentFrame) {
  46919. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  46920. startKeyIndex--;
  46921. }
  46922. }
  46923. for (var key = startKeyIndex; key < keys.length; key++) {
  46924. var endKey = keys[key + 1];
  46925. if (endKey.frame >= currentFrame) {
  46926. var startKey = keys[key];
  46927. var startValue = this._getKeyValue(startKey.value);
  46928. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  46929. return startValue;
  46930. }
  46931. var endValue = this._getKeyValue(endKey.value);
  46932. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  46933. var frameDelta = endKey.frame - startKey.frame;
  46934. // gradient : percent of currentFrame between the frame inf and the frame sup
  46935. var gradient = (currentFrame - startKey.frame) / frameDelta;
  46936. // check for easingFunction and correction of gradient
  46937. var easingFunction = this._animation.getEasingFunction();
  46938. if (easingFunction != null) {
  46939. gradient = easingFunction.ease(gradient);
  46940. }
  46941. switch (this._animation.dataType) {
  46942. // Float
  46943. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46944. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  46945. switch (loopMode) {
  46946. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46947. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46948. return floatValue;
  46949. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46950. return offsetValue * repeatCount + floatValue;
  46951. }
  46952. break;
  46953. // Quaternion
  46954. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46955. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  46956. switch (loopMode) {
  46957. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46958. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46959. return quatValue;
  46960. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46961. return quatValue.add(offsetValue.scale(repeatCount));
  46962. }
  46963. return quatValue;
  46964. // Vector3
  46965. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46966. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  46967. switch (loopMode) {
  46968. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46969. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46970. return vec3Value;
  46971. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46972. return vec3Value.add(offsetValue.scale(repeatCount));
  46973. }
  46974. // Vector2
  46975. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46976. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  46977. switch (loopMode) {
  46978. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46979. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46980. return vec2Value;
  46981. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46982. return vec2Value.add(offsetValue.scale(repeatCount));
  46983. }
  46984. // Size
  46985. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46986. switch (loopMode) {
  46987. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46988. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46989. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  46990. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46991. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  46992. }
  46993. // Color3
  46994. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46995. switch (loopMode) {
  46996. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46997. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46998. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  46999. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47000. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47001. }
  47002. // Matrix
  47003. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47004. switch (loopMode) {
  47005. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47006. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47007. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47008. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47009. }
  47010. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47011. return startValue;
  47012. }
  47013. default:
  47014. break;
  47015. }
  47016. break;
  47017. }
  47018. }
  47019. return this._getKeyValue(keys[keys.length - 1].value);
  47020. };
  47021. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  47022. if (blend === void 0) { blend = false; }
  47023. // Set value
  47024. var path;
  47025. var destination;
  47026. var targetPropertyPath = this._animation.targetPropertyPath;
  47027. if (targetPropertyPath.length > 1) {
  47028. var property = this._target[targetPropertyPath[0]];
  47029. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  47030. property = property[targetPropertyPath[index]];
  47031. }
  47032. path = targetPropertyPath[targetPropertyPath.length - 1];
  47033. destination = property;
  47034. }
  47035. else {
  47036. path = targetPropertyPath[0];
  47037. destination = this._target;
  47038. }
  47039. // Blending
  47040. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  47041. if (!this._originalBlendValue) {
  47042. if (destination[path].clone) {
  47043. this._originalBlendValue = destination[path].clone();
  47044. }
  47045. else {
  47046. this._originalBlendValue = destination[path];
  47047. }
  47048. }
  47049. if (this._originalBlendValue.prototype) {
  47050. if (this._originalBlendValue.prototype.Lerp) {
  47051. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  47052. }
  47053. else {
  47054. destination[path] = currentValue;
  47055. }
  47056. }
  47057. else if (this._originalBlendValue.m) {
  47058. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  47059. }
  47060. else {
  47061. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  47062. }
  47063. this._blendingFactor += this._animation.blendingSpeed;
  47064. }
  47065. else {
  47066. destination[path] = currentValue;
  47067. }
  47068. if (this._target.markAsDirty) {
  47069. this._target.markAsDirty(this._animation.targetProperty);
  47070. }
  47071. };
  47072. RuntimeAnimation.prototype.goToFrame = function (frame) {
  47073. var keys = this._animation.getKeys();
  47074. if (frame < keys[0].frame) {
  47075. frame = keys[0].frame;
  47076. }
  47077. else if (frame > keys[keys.length - 1].frame) {
  47078. frame = keys[keys.length - 1].frame;
  47079. }
  47080. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  47081. this.setValue(currentValue);
  47082. };
  47083. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  47084. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  47085. this._ratioOffset = this._previousRatio - newRatio;
  47086. };
  47087. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  47088. if (blend === void 0) { blend = false; }
  47089. var targetPropertyPath = this._animation.targetPropertyPath;
  47090. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  47091. this._stopped = true;
  47092. return false;
  47093. }
  47094. var returnValue = true;
  47095. var keys = this._animation.getKeys();
  47096. // Adding a start key at frame 0 if missing
  47097. if (keys[0].frame !== 0) {
  47098. var newKey = { frame: 0, value: keys[0].value };
  47099. keys.splice(0, 0, newKey);
  47100. }
  47101. // Check limits
  47102. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  47103. from = keys[0].frame;
  47104. }
  47105. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  47106. to = keys[keys.length - 1].frame;
  47107. }
  47108. //to and from cannot be the same key
  47109. if (from === to) {
  47110. if (from > keys[0].frame) {
  47111. from--;
  47112. }
  47113. else if (to < keys[keys.length - 1].frame) {
  47114. to++;
  47115. }
  47116. }
  47117. // Compute ratio
  47118. var range = to - from;
  47119. var offsetValue;
  47120. // ratio represents the frame delta between from and to
  47121. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  47122. var highLimitValue = 0;
  47123. this._previousDelay = delay;
  47124. this._previousRatio = ratio;
  47125. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  47126. returnValue = false;
  47127. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  47128. }
  47129. else {
  47130. // Get max value if required
  47131. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  47132. var keyOffset = to.toString() + from.toString();
  47133. if (!this._offsetsCache[keyOffset]) {
  47134. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47135. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47136. switch (this._animation.dataType) {
  47137. // Float
  47138. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47139. this._offsetsCache[keyOffset] = toValue - fromValue;
  47140. break;
  47141. // Quaternion
  47142. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47143. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47144. break;
  47145. // Vector3
  47146. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47147. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47148. // Vector2
  47149. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47150. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47151. // Size
  47152. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47153. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47154. // Color3
  47155. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47156. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47157. default:
  47158. break;
  47159. }
  47160. this._highLimitsCache[keyOffset] = toValue;
  47161. }
  47162. highLimitValue = this._highLimitsCache[keyOffset];
  47163. offsetValue = this._offsetsCache[keyOffset];
  47164. }
  47165. }
  47166. if (offsetValue === undefined) {
  47167. switch (this._animation.dataType) {
  47168. // Float
  47169. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47170. offsetValue = 0;
  47171. break;
  47172. // Quaternion
  47173. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47174. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  47175. break;
  47176. // Vector3
  47177. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47178. offsetValue = BABYLON.Vector3.Zero();
  47179. break;
  47180. // Vector2
  47181. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47182. offsetValue = BABYLON.Vector2.Zero();
  47183. break;
  47184. // Size
  47185. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47186. offsetValue = BABYLON.Size.Zero();
  47187. break;
  47188. // Color3
  47189. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47190. offsetValue = BABYLON.Color3.Black();
  47191. }
  47192. }
  47193. // Compute value
  47194. var repeatCount = (ratio / range) >> 0;
  47195. var currentFrame = returnValue ? from + ratio % range : to;
  47196. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  47197. // Set value
  47198. this.setValue(currentValue);
  47199. // Check events
  47200. var events = this._animation.getEvents();
  47201. for (var index = 0; index < events.length; index++) {
  47202. // Make sure current frame has passed event frame and that event frame is within the current range
  47203. // Also, handle both forward and reverse animations
  47204. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  47205. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  47206. var event = events[index];
  47207. if (!event.isDone) {
  47208. // If event should be done only once, remove it.
  47209. if (event.onlyOnce) {
  47210. events.splice(index, 1);
  47211. index--;
  47212. }
  47213. event.isDone = true;
  47214. event.action();
  47215. } // Don't do anything if the event has already be done.
  47216. }
  47217. else if (events[index].isDone && !events[index].onlyOnce) {
  47218. // reset event, the animation is looping
  47219. events[index].isDone = false;
  47220. }
  47221. }
  47222. if (!returnValue) {
  47223. this._stopped = true;
  47224. }
  47225. return returnValue;
  47226. };
  47227. return RuntimeAnimation;
  47228. }());
  47229. BABYLON.RuntimeAnimation = RuntimeAnimation;
  47230. })(BABYLON || (BABYLON = {}));
  47231. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  47232. var BABYLON;
  47233. (function (BABYLON) {
  47234. var Animatable = /** @class */ (function () {
  47235. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  47236. if (fromFrame === void 0) { fromFrame = 0; }
  47237. if (toFrame === void 0) { toFrame = 100; }
  47238. if (loopAnimation === void 0) { loopAnimation = false; }
  47239. if (speedRatio === void 0) { speedRatio = 1.0; }
  47240. this.target = target;
  47241. this.fromFrame = fromFrame;
  47242. this.toFrame = toFrame;
  47243. this.loopAnimation = loopAnimation;
  47244. this.onAnimationEnd = onAnimationEnd;
  47245. this._localDelayOffset = null;
  47246. this._pausedDelay = null;
  47247. this._runtimeAnimations = new Array();
  47248. this._paused = false;
  47249. this._speedRatio = 1;
  47250. this.animationStarted = false;
  47251. if (animations) {
  47252. this.appendAnimations(target, animations);
  47253. }
  47254. this._speedRatio = speedRatio;
  47255. this._scene = scene;
  47256. scene._activeAnimatables.push(this);
  47257. }
  47258. Object.defineProperty(Animatable.prototype, "speedRatio", {
  47259. get: function () {
  47260. return this._speedRatio;
  47261. },
  47262. set: function (value) {
  47263. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  47264. var animation = this._runtimeAnimations[index];
  47265. animation._prepareForSpeedRatioChange(value);
  47266. }
  47267. this._speedRatio = value;
  47268. },
  47269. enumerable: true,
  47270. configurable: true
  47271. });
  47272. // Methods
  47273. Animatable.prototype.getAnimations = function () {
  47274. return this._runtimeAnimations;
  47275. };
  47276. Animatable.prototype.appendAnimations = function (target, animations) {
  47277. for (var index = 0; index < animations.length; index++) {
  47278. var animation = animations[index];
  47279. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  47280. }
  47281. };
  47282. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  47283. var runtimeAnimations = this._runtimeAnimations;
  47284. for (var index = 0; index < runtimeAnimations.length; index++) {
  47285. if (runtimeAnimations[index].animation.targetProperty === property) {
  47286. return runtimeAnimations[index].animation;
  47287. }
  47288. }
  47289. return null;
  47290. };
  47291. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  47292. var runtimeAnimations = this._runtimeAnimations;
  47293. for (var index = 0; index < runtimeAnimations.length; index++) {
  47294. if (runtimeAnimations[index].animation.targetProperty === property) {
  47295. return runtimeAnimations[index];
  47296. }
  47297. }
  47298. return null;
  47299. };
  47300. Animatable.prototype.reset = function () {
  47301. var runtimeAnimations = this._runtimeAnimations;
  47302. for (var index = 0; index < runtimeAnimations.length; index++) {
  47303. runtimeAnimations[index].reset();
  47304. }
  47305. // Reset to original value
  47306. for (index = 0; index < runtimeAnimations.length; index++) {
  47307. var animation = runtimeAnimations[index];
  47308. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  47309. }
  47310. this._localDelayOffset = null;
  47311. this._pausedDelay = null;
  47312. };
  47313. Animatable.prototype.enableBlending = function (blendingSpeed) {
  47314. var runtimeAnimations = this._runtimeAnimations;
  47315. for (var index = 0; index < runtimeAnimations.length; index++) {
  47316. runtimeAnimations[index].animation.enableBlending = true;
  47317. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  47318. }
  47319. };
  47320. Animatable.prototype.disableBlending = function () {
  47321. var runtimeAnimations = this._runtimeAnimations;
  47322. for (var index = 0; index < runtimeAnimations.length; index++) {
  47323. runtimeAnimations[index].animation.enableBlending = false;
  47324. }
  47325. };
  47326. Animatable.prototype.goToFrame = function (frame) {
  47327. var runtimeAnimations = this._runtimeAnimations;
  47328. if (runtimeAnimations[0]) {
  47329. var fps = runtimeAnimations[0].animation.framePerSecond;
  47330. var currentFrame = runtimeAnimations[0].currentFrame;
  47331. var adjustTime = frame - currentFrame;
  47332. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  47333. if (this._localDelayOffset === null) {
  47334. this._localDelayOffset = 0;
  47335. }
  47336. this._localDelayOffset -= delay;
  47337. }
  47338. for (var index = 0; index < runtimeAnimations.length; index++) {
  47339. runtimeAnimations[index].goToFrame(frame);
  47340. }
  47341. };
  47342. Animatable.prototype.pause = function () {
  47343. if (this._paused) {
  47344. return;
  47345. }
  47346. this._paused = true;
  47347. };
  47348. Animatable.prototype.restart = function () {
  47349. this._paused = false;
  47350. };
  47351. Animatable.prototype.stop = function (animationName) {
  47352. if (animationName) {
  47353. var idx = this._scene._activeAnimatables.indexOf(this);
  47354. if (idx > -1) {
  47355. var runtimeAnimations = this._runtimeAnimations;
  47356. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  47357. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  47358. continue;
  47359. }
  47360. runtimeAnimations[index].dispose();
  47361. runtimeAnimations.splice(index, 1);
  47362. }
  47363. if (runtimeAnimations.length == 0) {
  47364. this._scene._activeAnimatables.splice(idx, 1);
  47365. if (this.onAnimationEnd) {
  47366. this.onAnimationEnd();
  47367. }
  47368. }
  47369. }
  47370. }
  47371. else {
  47372. var index = this._scene._activeAnimatables.indexOf(this);
  47373. if (index > -1) {
  47374. this._scene._activeAnimatables.splice(index, 1);
  47375. var runtimeAnimations = this._runtimeAnimations;
  47376. for (var index = 0; index < runtimeAnimations.length; index++) {
  47377. runtimeAnimations[index].dispose();
  47378. }
  47379. if (this.onAnimationEnd) {
  47380. this.onAnimationEnd();
  47381. }
  47382. }
  47383. }
  47384. };
  47385. Animatable.prototype._animate = function (delay) {
  47386. if (this._paused) {
  47387. this.animationStarted = false;
  47388. if (this._pausedDelay === null) {
  47389. this._pausedDelay = delay;
  47390. }
  47391. return true;
  47392. }
  47393. if (this._localDelayOffset === null) {
  47394. this._localDelayOffset = delay;
  47395. this._pausedDelay = null;
  47396. }
  47397. else if (this._pausedDelay !== null) {
  47398. this._localDelayOffset += delay - this._pausedDelay;
  47399. this._pausedDelay = null;
  47400. }
  47401. // Animating
  47402. var running = false;
  47403. var runtimeAnimations = this._runtimeAnimations;
  47404. var index;
  47405. for (index = 0; index < runtimeAnimations.length; index++) {
  47406. var animation = runtimeAnimations[index];
  47407. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  47408. running = running || isRunning;
  47409. }
  47410. this.animationStarted = running;
  47411. if (!running) {
  47412. // Remove from active animatables
  47413. index = this._scene._activeAnimatables.indexOf(this);
  47414. this._scene._activeAnimatables.splice(index, 1);
  47415. // Dispose all runtime animations
  47416. for (index = 0; index < runtimeAnimations.length; index++) {
  47417. runtimeAnimations[index].dispose();
  47418. }
  47419. }
  47420. if (!running && this.onAnimationEnd) {
  47421. this.onAnimationEnd();
  47422. this.onAnimationEnd = null;
  47423. }
  47424. return running;
  47425. };
  47426. return Animatable;
  47427. }());
  47428. BABYLON.Animatable = Animatable;
  47429. })(BABYLON || (BABYLON = {}));
  47430. //# sourceMappingURL=babylon.animatable.js.map
  47431. var BABYLON;
  47432. (function (BABYLON) {
  47433. var EasingFunction = /** @class */ (function () {
  47434. function EasingFunction() {
  47435. // Properties
  47436. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  47437. }
  47438. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  47439. get: function () {
  47440. return EasingFunction._EASINGMODE_EASEIN;
  47441. },
  47442. enumerable: true,
  47443. configurable: true
  47444. });
  47445. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  47446. get: function () {
  47447. return EasingFunction._EASINGMODE_EASEOUT;
  47448. },
  47449. enumerable: true,
  47450. configurable: true
  47451. });
  47452. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  47453. get: function () {
  47454. return EasingFunction._EASINGMODE_EASEINOUT;
  47455. },
  47456. enumerable: true,
  47457. configurable: true
  47458. });
  47459. EasingFunction.prototype.setEasingMode = function (easingMode) {
  47460. var n = Math.min(Math.max(easingMode, 0), 2);
  47461. this._easingMode = n;
  47462. };
  47463. EasingFunction.prototype.getEasingMode = function () {
  47464. return this._easingMode;
  47465. };
  47466. EasingFunction.prototype.easeInCore = function (gradient) {
  47467. throw new Error('You must implement this method');
  47468. };
  47469. EasingFunction.prototype.ease = function (gradient) {
  47470. switch (this._easingMode) {
  47471. case EasingFunction.EASINGMODE_EASEIN:
  47472. return this.easeInCore(gradient);
  47473. case EasingFunction.EASINGMODE_EASEOUT:
  47474. return (1 - this.easeInCore(1 - gradient));
  47475. }
  47476. if (gradient >= 0.5) {
  47477. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  47478. }
  47479. return (this.easeInCore(gradient * 2) * 0.5);
  47480. };
  47481. //Statics
  47482. EasingFunction._EASINGMODE_EASEIN = 0;
  47483. EasingFunction._EASINGMODE_EASEOUT = 1;
  47484. EasingFunction._EASINGMODE_EASEINOUT = 2;
  47485. return EasingFunction;
  47486. }());
  47487. BABYLON.EasingFunction = EasingFunction;
  47488. var CircleEase = /** @class */ (function (_super) {
  47489. __extends(CircleEase, _super);
  47490. function CircleEase() {
  47491. return _super !== null && _super.apply(this, arguments) || this;
  47492. }
  47493. CircleEase.prototype.easeInCore = function (gradient) {
  47494. gradient = Math.max(0, Math.min(1, gradient));
  47495. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  47496. };
  47497. return CircleEase;
  47498. }(EasingFunction));
  47499. BABYLON.CircleEase = CircleEase;
  47500. var BackEase = /** @class */ (function (_super) {
  47501. __extends(BackEase, _super);
  47502. function BackEase(amplitude) {
  47503. if (amplitude === void 0) { amplitude = 1; }
  47504. var _this = _super.call(this) || this;
  47505. _this.amplitude = amplitude;
  47506. return _this;
  47507. }
  47508. BackEase.prototype.easeInCore = function (gradient) {
  47509. var num = Math.max(0, this.amplitude);
  47510. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  47511. };
  47512. return BackEase;
  47513. }(EasingFunction));
  47514. BABYLON.BackEase = BackEase;
  47515. var BounceEase = /** @class */ (function (_super) {
  47516. __extends(BounceEase, _super);
  47517. function BounceEase(bounces, bounciness) {
  47518. if (bounces === void 0) { bounces = 3; }
  47519. if (bounciness === void 0) { bounciness = 2; }
  47520. var _this = _super.call(this) || this;
  47521. _this.bounces = bounces;
  47522. _this.bounciness = bounciness;
  47523. return _this;
  47524. }
  47525. BounceEase.prototype.easeInCore = function (gradient) {
  47526. var y = Math.max(0.0, this.bounces);
  47527. var bounciness = this.bounciness;
  47528. if (bounciness <= 1.0) {
  47529. bounciness = 1.001;
  47530. }
  47531. var num9 = Math.pow(bounciness, y);
  47532. var num5 = 1.0 - bounciness;
  47533. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  47534. var num15 = gradient * num4;
  47535. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  47536. var num3 = Math.floor(num65);
  47537. var num13 = num3 + 1.0;
  47538. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  47539. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  47540. var num7 = (num8 + num12) * 0.5;
  47541. var num6 = gradient - num7;
  47542. var num2 = num7 - num8;
  47543. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  47544. };
  47545. return BounceEase;
  47546. }(EasingFunction));
  47547. BABYLON.BounceEase = BounceEase;
  47548. var CubicEase = /** @class */ (function (_super) {
  47549. __extends(CubicEase, _super);
  47550. function CubicEase() {
  47551. return _super !== null && _super.apply(this, arguments) || this;
  47552. }
  47553. CubicEase.prototype.easeInCore = function (gradient) {
  47554. return (gradient * gradient * gradient);
  47555. };
  47556. return CubicEase;
  47557. }(EasingFunction));
  47558. BABYLON.CubicEase = CubicEase;
  47559. var ElasticEase = /** @class */ (function (_super) {
  47560. __extends(ElasticEase, _super);
  47561. function ElasticEase(oscillations, springiness) {
  47562. if (oscillations === void 0) { oscillations = 3; }
  47563. if (springiness === void 0) { springiness = 3; }
  47564. var _this = _super.call(this) || this;
  47565. _this.oscillations = oscillations;
  47566. _this.springiness = springiness;
  47567. return _this;
  47568. }
  47569. ElasticEase.prototype.easeInCore = function (gradient) {
  47570. var num2;
  47571. var num3 = Math.max(0.0, this.oscillations);
  47572. var num = Math.max(0.0, this.springiness);
  47573. if (num == 0) {
  47574. num2 = gradient;
  47575. }
  47576. else {
  47577. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  47578. }
  47579. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  47580. };
  47581. return ElasticEase;
  47582. }(EasingFunction));
  47583. BABYLON.ElasticEase = ElasticEase;
  47584. var ExponentialEase = /** @class */ (function (_super) {
  47585. __extends(ExponentialEase, _super);
  47586. function ExponentialEase(exponent) {
  47587. if (exponent === void 0) { exponent = 2; }
  47588. var _this = _super.call(this) || this;
  47589. _this.exponent = exponent;
  47590. return _this;
  47591. }
  47592. ExponentialEase.prototype.easeInCore = function (gradient) {
  47593. if (this.exponent <= 0) {
  47594. return gradient;
  47595. }
  47596. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  47597. };
  47598. return ExponentialEase;
  47599. }(EasingFunction));
  47600. BABYLON.ExponentialEase = ExponentialEase;
  47601. var PowerEase = /** @class */ (function (_super) {
  47602. __extends(PowerEase, _super);
  47603. function PowerEase(power) {
  47604. if (power === void 0) { power = 2; }
  47605. var _this = _super.call(this) || this;
  47606. _this.power = power;
  47607. return _this;
  47608. }
  47609. PowerEase.prototype.easeInCore = function (gradient) {
  47610. var y = Math.max(0.0, this.power);
  47611. return Math.pow(gradient, y);
  47612. };
  47613. return PowerEase;
  47614. }(EasingFunction));
  47615. BABYLON.PowerEase = PowerEase;
  47616. var QuadraticEase = /** @class */ (function (_super) {
  47617. __extends(QuadraticEase, _super);
  47618. function QuadraticEase() {
  47619. return _super !== null && _super.apply(this, arguments) || this;
  47620. }
  47621. QuadraticEase.prototype.easeInCore = function (gradient) {
  47622. return (gradient * gradient);
  47623. };
  47624. return QuadraticEase;
  47625. }(EasingFunction));
  47626. BABYLON.QuadraticEase = QuadraticEase;
  47627. var QuarticEase = /** @class */ (function (_super) {
  47628. __extends(QuarticEase, _super);
  47629. function QuarticEase() {
  47630. return _super !== null && _super.apply(this, arguments) || this;
  47631. }
  47632. QuarticEase.prototype.easeInCore = function (gradient) {
  47633. return (gradient * gradient * gradient * gradient);
  47634. };
  47635. return QuarticEase;
  47636. }(EasingFunction));
  47637. BABYLON.QuarticEase = QuarticEase;
  47638. var QuinticEase = /** @class */ (function (_super) {
  47639. __extends(QuinticEase, _super);
  47640. function QuinticEase() {
  47641. return _super !== null && _super.apply(this, arguments) || this;
  47642. }
  47643. QuinticEase.prototype.easeInCore = function (gradient) {
  47644. return (gradient * gradient * gradient * gradient * gradient);
  47645. };
  47646. return QuinticEase;
  47647. }(EasingFunction));
  47648. BABYLON.QuinticEase = QuinticEase;
  47649. var SineEase = /** @class */ (function (_super) {
  47650. __extends(SineEase, _super);
  47651. function SineEase() {
  47652. return _super !== null && _super.apply(this, arguments) || this;
  47653. }
  47654. SineEase.prototype.easeInCore = function (gradient) {
  47655. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  47656. };
  47657. return SineEase;
  47658. }(EasingFunction));
  47659. BABYLON.SineEase = SineEase;
  47660. var BezierCurveEase = /** @class */ (function (_super) {
  47661. __extends(BezierCurveEase, _super);
  47662. function BezierCurveEase(x1, y1, x2, y2) {
  47663. if (x1 === void 0) { x1 = 0; }
  47664. if (y1 === void 0) { y1 = 0; }
  47665. if (x2 === void 0) { x2 = 1; }
  47666. if (y2 === void 0) { y2 = 1; }
  47667. var _this = _super.call(this) || this;
  47668. _this.x1 = x1;
  47669. _this.y1 = y1;
  47670. _this.x2 = x2;
  47671. _this.y2 = y2;
  47672. return _this;
  47673. }
  47674. BezierCurveEase.prototype.easeInCore = function (gradient) {
  47675. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  47676. };
  47677. return BezierCurveEase;
  47678. }(EasingFunction));
  47679. BABYLON.BezierCurveEase = BezierCurveEase;
  47680. })(BABYLON || (BABYLON = {}));
  47681. //# sourceMappingURL=babylon.easing.js.map
  47682. var BABYLON;
  47683. (function (BABYLON) {
  47684. var Condition = /** @class */ (function () {
  47685. function Condition(actionManager) {
  47686. this._actionManager = actionManager;
  47687. }
  47688. Condition.prototype.isValid = function () {
  47689. return true;
  47690. };
  47691. Condition.prototype._getProperty = function (propertyPath) {
  47692. return this._actionManager._getProperty(propertyPath);
  47693. };
  47694. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  47695. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47696. };
  47697. Condition.prototype.serialize = function () {
  47698. };
  47699. Condition.prototype._serialize = function (serializedCondition) {
  47700. return {
  47701. type: 2,
  47702. children: [],
  47703. name: serializedCondition.name,
  47704. properties: serializedCondition.properties
  47705. };
  47706. };
  47707. return Condition;
  47708. }());
  47709. BABYLON.Condition = Condition;
  47710. var ValueCondition = /** @class */ (function (_super) {
  47711. __extends(ValueCondition, _super);
  47712. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  47713. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  47714. var _this = _super.call(this, actionManager) || this;
  47715. _this.propertyPath = propertyPath;
  47716. _this.value = value;
  47717. _this.operator = operator;
  47718. _this._target = target;
  47719. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  47720. _this._property = _this._getProperty(_this.propertyPath);
  47721. return _this;
  47722. }
  47723. Object.defineProperty(ValueCondition, "IsEqual", {
  47724. get: function () {
  47725. return ValueCondition._IsEqual;
  47726. },
  47727. enumerable: true,
  47728. configurable: true
  47729. });
  47730. Object.defineProperty(ValueCondition, "IsDifferent", {
  47731. get: function () {
  47732. return ValueCondition._IsDifferent;
  47733. },
  47734. enumerable: true,
  47735. configurable: true
  47736. });
  47737. Object.defineProperty(ValueCondition, "IsGreater", {
  47738. get: function () {
  47739. return ValueCondition._IsGreater;
  47740. },
  47741. enumerable: true,
  47742. configurable: true
  47743. });
  47744. Object.defineProperty(ValueCondition, "IsLesser", {
  47745. get: function () {
  47746. return ValueCondition._IsLesser;
  47747. },
  47748. enumerable: true,
  47749. configurable: true
  47750. });
  47751. // Methods
  47752. ValueCondition.prototype.isValid = function () {
  47753. switch (this.operator) {
  47754. case ValueCondition.IsGreater:
  47755. return this._effectiveTarget[this._property] > this.value;
  47756. case ValueCondition.IsLesser:
  47757. return this._effectiveTarget[this._property] < this.value;
  47758. case ValueCondition.IsEqual:
  47759. case ValueCondition.IsDifferent:
  47760. var check;
  47761. if (this.value.equals) {
  47762. check = this.value.equals(this._effectiveTarget[this._property]);
  47763. }
  47764. else {
  47765. check = this.value === this._effectiveTarget[this._property];
  47766. }
  47767. return this.operator === ValueCondition.IsEqual ? check : !check;
  47768. }
  47769. return false;
  47770. };
  47771. ValueCondition.prototype.serialize = function () {
  47772. return this._serialize({
  47773. name: "ValueCondition",
  47774. properties: [
  47775. BABYLON.Action._GetTargetProperty(this._target),
  47776. { name: "propertyPath", value: this.propertyPath },
  47777. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  47778. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  47779. ]
  47780. });
  47781. };
  47782. ValueCondition.GetOperatorName = function (operator) {
  47783. switch (operator) {
  47784. case ValueCondition._IsEqual: return "IsEqual";
  47785. case ValueCondition._IsDifferent: return "IsDifferent";
  47786. case ValueCondition._IsGreater: return "IsGreater";
  47787. case ValueCondition._IsLesser: return "IsLesser";
  47788. default: return "";
  47789. }
  47790. };
  47791. // Statics
  47792. ValueCondition._IsEqual = 0;
  47793. ValueCondition._IsDifferent = 1;
  47794. ValueCondition._IsGreater = 2;
  47795. ValueCondition._IsLesser = 3;
  47796. return ValueCondition;
  47797. }(Condition));
  47798. BABYLON.ValueCondition = ValueCondition;
  47799. var PredicateCondition = /** @class */ (function (_super) {
  47800. __extends(PredicateCondition, _super);
  47801. function PredicateCondition(actionManager, predicate) {
  47802. var _this = _super.call(this, actionManager) || this;
  47803. _this.predicate = predicate;
  47804. return _this;
  47805. }
  47806. PredicateCondition.prototype.isValid = function () {
  47807. return this.predicate();
  47808. };
  47809. return PredicateCondition;
  47810. }(Condition));
  47811. BABYLON.PredicateCondition = PredicateCondition;
  47812. var StateCondition = /** @class */ (function (_super) {
  47813. __extends(StateCondition, _super);
  47814. function StateCondition(actionManager, target, value) {
  47815. var _this = _super.call(this, actionManager) || this;
  47816. _this.value = value;
  47817. _this._target = target;
  47818. return _this;
  47819. }
  47820. // Methods
  47821. StateCondition.prototype.isValid = function () {
  47822. return this._target.state === this.value;
  47823. };
  47824. StateCondition.prototype.serialize = function () {
  47825. return this._serialize({
  47826. name: "StateCondition",
  47827. properties: [
  47828. BABYLON.Action._GetTargetProperty(this._target),
  47829. { name: "value", value: this.value }
  47830. ]
  47831. });
  47832. };
  47833. return StateCondition;
  47834. }(Condition));
  47835. BABYLON.StateCondition = StateCondition;
  47836. })(BABYLON || (BABYLON = {}));
  47837. //# sourceMappingURL=babylon.condition.js.map
  47838. var BABYLON;
  47839. (function (BABYLON) {
  47840. var Action = /** @class */ (function () {
  47841. function Action(triggerOptions, condition) {
  47842. this.triggerOptions = triggerOptions;
  47843. this.onBeforeExecuteObservable = new BABYLON.Observable();
  47844. if (triggerOptions.parameter) {
  47845. this.trigger = triggerOptions.trigger;
  47846. this._triggerParameter = triggerOptions.parameter;
  47847. }
  47848. else {
  47849. this.trigger = triggerOptions;
  47850. }
  47851. this._nextActiveAction = this;
  47852. this._condition = condition;
  47853. }
  47854. // Methods
  47855. Action.prototype._prepare = function () {
  47856. };
  47857. Action.prototype.getTriggerParameter = function () {
  47858. return this._triggerParameter;
  47859. };
  47860. Action.prototype._executeCurrent = function (evt) {
  47861. if (this._nextActiveAction._condition) {
  47862. var condition = this._nextActiveAction._condition;
  47863. var currentRenderId = this._actionManager.getScene().getRenderId();
  47864. // We cache the current evaluation for the current frame
  47865. if (condition._evaluationId === currentRenderId) {
  47866. if (!condition._currentResult) {
  47867. return;
  47868. }
  47869. }
  47870. else {
  47871. condition._evaluationId = currentRenderId;
  47872. if (!condition.isValid()) {
  47873. condition._currentResult = false;
  47874. return;
  47875. }
  47876. condition._currentResult = true;
  47877. }
  47878. }
  47879. this.onBeforeExecuteObservable.notifyObservers(this);
  47880. this._nextActiveAction.execute(evt);
  47881. this.skipToNextActiveAction();
  47882. };
  47883. Action.prototype.execute = function (evt) {
  47884. };
  47885. Action.prototype.skipToNextActiveAction = function () {
  47886. if (this._nextActiveAction._child) {
  47887. if (!this._nextActiveAction._child._actionManager) {
  47888. this._nextActiveAction._child._actionManager = this._actionManager;
  47889. }
  47890. this._nextActiveAction = this._nextActiveAction._child;
  47891. }
  47892. else {
  47893. this._nextActiveAction = this;
  47894. }
  47895. };
  47896. Action.prototype.then = function (action) {
  47897. this._child = action;
  47898. action._actionManager = this._actionManager;
  47899. action._prepare();
  47900. return action;
  47901. };
  47902. Action.prototype._getProperty = function (propertyPath) {
  47903. return this._actionManager._getProperty(propertyPath);
  47904. };
  47905. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  47906. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47907. };
  47908. Action.prototype.serialize = function (parent) {
  47909. };
  47910. // Called by BABYLON.Action objects in serialize(...). Internal use
  47911. Action.prototype._serialize = function (serializedAction, parent) {
  47912. var serializationObject = {
  47913. type: 1,
  47914. children: [],
  47915. name: serializedAction.name,
  47916. properties: serializedAction.properties || []
  47917. };
  47918. // Serialize child
  47919. if (this._child) {
  47920. this._child.serialize(serializationObject);
  47921. }
  47922. // Check if "this" has a condition
  47923. if (this._condition) {
  47924. var serializedCondition = this._condition.serialize();
  47925. serializedCondition.children.push(serializationObject);
  47926. if (parent) {
  47927. parent.children.push(serializedCondition);
  47928. }
  47929. return serializedCondition;
  47930. }
  47931. if (parent) {
  47932. parent.children.push(serializationObject);
  47933. }
  47934. return serializationObject;
  47935. };
  47936. Action._SerializeValueAsString = function (value) {
  47937. if (typeof value === "number") {
  47938. return value.toString();
  47939. }
  47940. if (typeof value === "boolean") {
  47941. return value ? "true" : "false";
  47942. }
  47943. if (value instanceof BABYLON.Vector2) {
  47944. return value.x + ", " + value.y;
  47945. }
  47946. if (value instanceof BABYLON.Vector3) {
  47947. return value.x + ", " + value.y + ", " + value.z;
  47948. }
  47949. if (value instanceof BABYLON.Color3) {
  47950. return value.r + ", " + value.g + ", " + value.b;
  47951. }
  47952. if (value instanceof BABYLON.Color4) {
  47953. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  47954. }
  47955. return value; // string
  47956. };
  47957. Action._GetTargetProperty = function (target) {
  47958. return {
  47959. name: "target",
  47960. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  47961. : target instanceof BABYLON.Light ? "LightProperties"
  47962. : target instanceof BABYLON.Camera ? "CameraProperties"
  47963. : "SceneProperties",
  47964. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  47965. };
  47966. };
  47967. return Action;
  47968. }());
  47969. BABYLON.Action = Action;
  47970. })(BABYLON || (BABYLON = {}));
  47971. //# sourceMappingURL=babylon.action.js.map
  47972. var BABYLON;
  47973. (function (BABYLON) {
  47974. /**
  47975. * ActionEvent is the event beint sent when an action is triggered.
  47976. */
  47977. var ActionEvent = /** @class */ (function () {
  47978. /**
  47979. * @param source The mesh or sprite that triggered the action.
  47980. * @param pointerX The X mouse cursor position at the time of the event
  47981. * @param pointerY The Y mouse cursor position at the time of the event
  47982. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  47983. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  47984. */
  47985. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  47986. this.source = source;
  47987. this.pointerX = pointerX;
  47988. this.pointerY = pointerY;
  47989. this.meshUnderPointer = meshUnderPointer;
  47990. this.sourceEvent = sourceEvent;
  47991. this.additionalData = additionalData;
  47992. }
  47993. /**
  47994. * Helper function to auto-create an ActionEvent from a source mesh.
  47995. * @param source The source mesh that triggered the event
  47996. * @param evt {Event} The original (browser) event
  47997. */
  47998. ActionEvent.CreateNew = function (source, evt, additionalData) {
  47999. var scene = source.getScene();
  48000. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48001. };
  48002. /**
  48003. * Helper function to auto-create an ActionEvent from a source mesh.
  48004. * @param source The source sprite that triggered the event
  48005. * @param scene Scene associated with the sprite
  48006. * @param evt {Event} The original (browser) event
  48007. */
  48008. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  48009. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48010. };
  48011. /**
  48012. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  48013. * @param scene the scene where the event occurred
  48014. * @param evt {Event} The original (browser) event
  48015. */
  48016. ActionEvent.CreateNewFromScene = function (scene, evt) {
  48017. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  48018. };
  48019. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  48020. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  48021. };
  48022. return ActionEvent;
  48023. }());
  48024. BABYLON.ActionEvent = ActionEvent;
  48025. /**
  48026. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  48027. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  48028. */
  48029. var ActionManager = /** @class */ (function () {
  48030. function ActionManager(scene) {
  48031. // Members
  48032. this.actions = new Array();
  48033. this.hoverCursor = '';
  48034. this._scene = scene;
  48035. scene._actionManagers.push(this);
  48036. }
  48037. Object.defineProperty(ActionManager, "NothingTrigger", {
  48038. get: function () {
  48039. return ActionManager._NothingTrigger;
  48040. },
  48041. enumerable: true,
  48042. configurable: true
  48043. });
  48044. Object.defineProperty(ActionManager, "OnPickTrigger", {
  48045. get: function () {
  48046. return ActionManager._OnPickTrigger;
  48047. },
  48048. enumerable: true,
  48049. configurable: true
  48050. });
  48051. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  48052. get: function () {
  48053. return ActionManager._OnLeftPickTrigger;
  48054. },
  48055. enumerable: true,
  48056. configurable: true
  48057. });
  48058. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  48059. get: function () {
  48060. return ActionManager._OnRightPickTrigger;
  48061. },
  48062. enumerable: true,
  48063. configurable: true
  48064. });
  48065. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  48066. get: function () {
  48067. return ActionManager._OnCenterPickTrigger;
  48068. },
  48069. enumerable: true,
  48070. configurable: true
  48071. });
  48072. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  48073. get: function () {
  48074. return ActionManager._OnPickDownTrigger;
  48075. },
  48076. enumerable: true,
  48077. configurable: true
  48078. });
  48079. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  48080. get: function () {
  48081. return ActionManager._OnDoublePickTrigger;
  48082. },
  48083. enumerable: true,
  48084. configurable: true
  48085. });
  48086. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  48087. get: function () {
  48088. return ActionManager._OnPickUpTrigger;
  48089. },
  48090. enumerable: true,
  48091. configurable: true
  48092. });
  48093. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  48094. /// This trigger will only be raised if you also declared a OnPickDown
  48095. get: function () {
  48096. return ActionManager._OnPickOutTrigger;
  48097. },
  48098. enumerable: true,
  48099. configurable: true
  48100. });
  48101. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  48102. get: function () {
  48103. return ActionManager._OnLongPressTrigger;
  48104. },
  48105. enumerable: true,
  48106. configurable: true
  48107. });
  48108. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  48109. get: function () {
  48110. return ActionManager._OnPointerOverTrigger;
  48111. },
  48112. enumerable: true,
  48113. configurable: true
  48114. });
  48115. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  48116. get: function () {
  48117. return ActionManager._OnPointerOutTrigger;
  48118. },
  48119. enumerable: true,
  48120. configurable: true
  48121. });
  48122. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  48123. get: function () {
  48124. return ActionManager._OnEveryFrameTrigger;
  48125. },
  48126. enumerable: true,
  48127. configurable: true
  48128. });
  48129. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  48130. get: function () {
  48131. return ActionManager._OnIntersectionEnterTrigger;
  48132. },
  48133. enumerable: true,
  48134. configurable: true
  48135. });
  48136. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  48137. get: function () {
  48138. return ActionManager._OnIntersectionExitTrigger;
  48139. },
  48140. enumerable: true,
  48141. configurable: true
  48142. });
  48143. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  48144. get: function () {
  48145. return ActionManager._OnKeyDownTrigger;
  48146. },
  48147. enumerable: true,
  48148. configurable: true
  48149. });
  48150. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  48151. get: function () {
  48152. return ActionManager._OnKeyUpTrigger;
  48153. },
  48154. enumerable: true,
  48155. configurable: true
  48156. });
  48157. // Methods
  48158. ActionManager.prototype.dispose = function () {
  48159. var index = this._scene._actionManagers.indexOf(this);
  48160. for (var i = 0; i < this.actions.length; i++) {
  48161. var action = this.actions[i];
  48162. ActionManager.Triggers[action.trigger]--;
  48163. if (ActionManager.Triggers[action.trigger] === 0) {
  48164. delete ActionManager.Triggers[action.trigger];
  48165. }
  48166. }
  48167. if (index > -1) {
  48168. this._scene._actionManagers.splice(index, 1);
  48169. }
  48170. };
  48171. ActionManager.prototype.getScene = function () {
  48172. return this._scene;
  48173. };
  48174. /**
  48175. * Does this action manager handles actions of any of the given triggers
  48176. * @param {number[]} triggers - the triggers to be tested
  48177. * @return {boolean} whether one (or more) of the triggers is handeled
  48178. */
  48179. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  48180. for (var index = 0; index < this.actions.length; index++) {
  48181. var action = this.actions[index];
  48182. if (triggers.indexOf(action.trigger) > -1) {
  48183. return true;
  48184. }
  48185. }
  48186. return false;
  48187. };
  48188. /**
  48189. * Does this action manager handles actions of a given trigger
  48190. * @param {number} trigger - the trigger to be tested
  48191. * @return {boolean} whether the trigger is handeled
  48192. */
  48193. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  48194. for (var index = 0; index < this.actions.length; index++) {
  48195. var action = this.actions[index];
  48196. if (action.trigger === trigger) {
  48197. return true;
  48198. }
  48199. }
  48200. return false;
  48201. };
  48202. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  48203. /**
  48204. * Does this action manager has pointer triggers
  48205. * @return {boolean} whether or not it has pointer triggers
  48206. */
  48207. get: function () {
  48208. for (var index = 0; index < this.actions.length; index++) {
  48209. var action = this.actions[index];
  48210. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  48211. return true;
  48212. }
  48213. }
  48214. return false;
  48215. },
  48216. enumerable: true,
  48217. configurable: true
  48218. });
  48219. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  48220. /**
  48221. * Does this action manager has pick triggers
  48222. * @return {boolean} whether or not it has pick triggers
  48223. */
  48224. get: function () {
  48225. for (var index = 0; index < this.actions.length; index++) {
  48226. var action = this.actions[index];
  48227. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  48228. return true;
  48229. }
  48230. }
  48231. return false;
  48232. },
  48233. enumerable: true,
  48234. configurable: true
  48235. });
  48236. Object.defineProperty(ActionManager, "HasTriggers", {
  48237. /**
  48238. * Does exist one action manager with at least one trigger
  48239. * @return {boolean} whether or not it exists one action manager with one trigger
  48240. **/
  48241. get: function () {
  48242. for (var t in ActionManager.Triggers) {
  48243. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48244. return true;
  48245. }
  48246. }
  48247. return false;
  48248. },
  48249. enumerable: true,
  48250. configurable: true
  48251. });
  48252. Object.defineProperty(ActionManager, "HasPickTriggers", {
  48253. /**
  48254. * Does exist one action manager with at least one pick trigger
  48255. * @return {boolean} whether or not it exists one action manager with one pick trigger
  48256. **/
  48257. get: function () {
  48258. for (var t in ActionManager.Triggers) {
  48259. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48260. var t_int = parseInt(t);
  48261. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  48262. return true;
  48263. }
  48264. }
  48265. }
  48266. return false;
  48267. },
  48268. enumerable: true,
  48269. configurable: true
  48270. });
  48271. /**
  48272. * Does exist one action manager that handles actions of a given trigger
  48273. * @param {number} trigger - the trigger to be tested
  48274. * @return {boolean} whether the trigger is handeled by at least one action manager
  48275. **/
  48276. ActionManager.HasSpecificTrigger = function (trigger) {
  48277. for (var t in ActionManager.Triggers) {
  48278. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48279. var t_int = parseInt(t);
  48280. if (t_int === trigger) {
  48281. return true;
  48282. }
  48283. }
  48284. }
  48285. return false;
  48286. };
  48287. /**
  48288. * Registers an action to this action manager
  48289. * @param {BABYLON.Action} action - the action to be registered
  48290. * @return {BABYLON.Action} the action amended (prepared) after registration
  48291. */
  48292. ActionManager.prototype.registerAction = function (action) {
  48293. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  48294. if (this.getScene().actionManager !== this) {
  48295. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  48296. return null;
  48297. }
  48298. }
  48299. this.actions.push(action);
  48300. if (ActionManager.Triggers[action.trigger]) {
  48301. ActionManager.Triggers[action.trigger]++;
  48302. }
  48303. else {
  48304. ActionManager.Triggers[action.trigger] = 1;
  48305. }
  48306. action._actionManager = this;
  48307. action._prepare();
  48308. return action;
  48309. };
  48310. /**
  48311. * Unregisters an action to this action manager
  48312. * @param action The action to be unregistered
  48313. * @return whether the action has been unregistered
  48314. */
  48315. ActionManager.prototype.unregisterAction = function (action) {
  48316. var index = this.actions.indexOf(action);
  48317. if (index !== -1) {
  48318. this.actions.splice(index, 1);
  48319. ActionManager.Triggers[action.trigger] -= 1;
  48320. if (ActionManager.Triggers[action.trigger] === 0) {
  48321. delete ActionManager.Triggers[action.trigger];
  48322. }
  48323. delete action._actionManager;
  48324. return true;
  48325. }
  48326. return false;
  48327. };
  48328. /**
  48329. * Process a specific trigger
  48330. * @param {number} trigger - the trigger to process
  48331. * @param evt {BABYLON.ActionEvent} the event details to be processed
  48332. */
  48333. ActionManager.prototype.processTrigger = function (trigger, evt) {
  48334. for (var index = 0; index < this.actions.length; index++) {
  48335. var action = this.actions[index];
  48336. if (action.trigger === trigger) {
  48337. if (evt) {
  48338. if (trigger === ActionManager.OnKeyUpTrigger
  48339. || trigger === ActionManager.OnKeyDownTrigger) {
  48340. var parameter = action.getTriggerParameter();
  48341. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  48342. if (!parameter.toLowerCase) {
  48343. continue;
  48344. }
  48345. var lowerCase = parameter.toLowerCase();
  48346. if (lowerCase !== evt.sourceEvent.key) {
  48347. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  48348. var actualkey = String.fromCharCode(unicode).toLowerCase();
  48349. if (actualkey !== lowerCase) {
  48350. continue;
  48351. }
  48352. }
  48353. }
  48354. }
  48355. }
  48356. action._executeCurrent(evt);
  48357. }
  48358. }
  48359. };
  48360. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  48361. var properties = propertyPath.split(".");
  48362. for (var index = 0; index < properties.length - 1; index++) {
  48363. target = target[properties[index]];
  48364. }
  48365. return target;
  48366. };
  48367. ActionManager.prototype._getProperty = function (propertyPath) {
  48368. var properties = propertyPath.split(".");
  48369. return properties[properties.length - 1];
  48370. };
  48371. ActionManager.prototype.serialize = function (name) {
  48372. var root = {
  48373. children: new Array(),
  48374. name: name,
  48375. type: 3,
  48376. properties: new Array() // Empty for root but required
  48377. };
  48378. for (var i = 0; i < this.actions.length; i++) {
  48379. var triggerObject = {
  48380. type: 0,
  48381. children: new Array(),
  48382. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  48383. properties: new Array()
  48384. };
  48385. var triggerOptions = this.actions[i].triggerOptions;
  48386. if (triggerOptions && typeof triggerOptions !== "number") {
  48387. if (triggerOptions.parameter instanceof BABYLON.Node) {
  48388. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  48389. }
  48390. else {
  48391. var parameter = {};
  48392. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  48393. if (triggerOptions.parameter.mesh) {
  48394. parameter._meshId = triggerOptions.parameter.mesh.id;
  48395. }
  48396. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  48397. }
  48398. }
  48399. // Serialize child action, recursively
  48400. this.actions[i].serialize(triggerObject);
  48401. // Add serialized trigger
  48402. root.children.push(triggerObject);
  48403. }
  48404. return root;
  48405. };
  48406. ActionManager.Parse = function (parsedActions, object, scene) {
  48407. var actionManager = new ActionManager(scene);
  48408. if (object === null)
  48409. scene.actionManager = actionManager;
  48410. else
  48411. object.actionManager = actionManager;
  48412. // instanciate a new object
  48413. var instanciate = function (name, params) {
  48414. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  48415. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  48416. newInstance.constructor.apply(newInstance, params);
  48417. return newInstance;
  48418. };
  48419. var parseParameter = function (name, value, target, propertyPath) {
  48420. if (propertyPath === null) {
  48421. // String, boolean or float
  48422. var floatValue = parseFloat(value);
  48423. if (value === "true" || value === "false")
  48424. return value === "true";
  48425. else
  48426. return isNaN(floatValue) ? value : floatValue;
  48427. }
  48428. var effectiveTarget = propertyPath.split(".");
  48429. var values = value.split(",");
  48430. // Get effective Target
  48431. for (var i = 0; i < effectiveTarget.length; i++) {
  48432. target = target[effectiveTarget[i]];
  48433. }
  48434. // Return appropriate value with its type
  48435. if (typeof (target) === "boolean")
  48436. return values[0] === "true";
  48437. if (typeof (target) === "string")
  48438. return values[0];
  48439. // Parameters with multiple values such as Vector3 etc.
  48440. var split = new Array();
  48441. for (var i = 0; i < values.length; i++)
  48442. split.push(parseFloat(values[i]));
  48443. if (target instanceof BABYLON.Vector3)
  48444. return BABYLON.Vector3.FromArray(split);
  48445. if (target instanceof BABYLON.Vector4)
  48446. return BABYLON.Vector4.FromArray(split);
  48447. if (target instanceof BABYLON.Color3)
  48448. return BABYLON.Color3.FromArray(split);
  48449. if (target instanceof BABYLON.Color4)
  48450. return BABYLON.Color4.FromArray(split);
  48451. return parseFloat(values[0]);
  48452. };
  48453. // traverse graph per trigger
  48454. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  48455. if (combineArray === void 0) { combineArray = null; }
  48456. if (parsedAction.detached)
  48457. return;
  48458. var parameters = new Array();
  48459. var target = null;
  48460. var propertyPath = null;
  48461. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  48462. // Parameters
  48463. if (parsedAction.type === 2)
  48464. parameters.push(actionManager);
  48465. else
  48466. parameters.push(trigger);
  48467. if (combine) {
  48468. var actions = new Array();
  48469. for (var j = 0; j < parsedAction.combine.length; j++) {
  48470. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  48471. }
  48472. parameters.push(actions);
  48473. }
  48474. else {
  48475. for (var i = 0; i < parsedAction.properties.length; i++) {
  48476. var value = parsedAction.properties[i].value;
  48477. var name = parsedAction.properties[i].name;
  48478. var targetType = parsedAction.properties[i].targetType;
  48479. if (name === "target")
  48480. if (targetType !== null && targetType === "SceneProperties")
  48481. value = target = scene;
  48482. else
  48483. value = target = scene.getNodeByName(value);
  48484. else if (name === "parent")
  48485. value = scene.getNodeByName(value);
  48486. else if (name === "sound")
  48487. value = scene.getSoundByName(value);
  48488. else if (name !== "propertyPath") {
  48489. if (parsedAction.type === 2 && name === "operator")
  48490. value = BABYLON.ValueCondition[value];
  48491. else
  48492. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  48493. }
  48494. else {
  48495. propertyPath = value;
  48496. }
  48497. parameters.push(value);
  48498. }
  48499. }
  48500. if (combineArray === null) {
  48501. parameters.push(condition);
  48502. }
  48503. else {
  48504. parameters.push(null);
  48505. }
  48506. // If interpolate value action
  48507. if (parsedAction.name === "InterpolateValueAction") {
  48508. var param = parameters[parameters.length - 2];
  48509. parameters[parameters.length - 1] = param;
  48510. parameters[parameters.length - 2] = condition;
  48511. }
  48512. // Action or condition(s) and not CombineAction
  48513. var newAction = instanciate(parsedAction.name, parameters);
  48514. if (newAction instanceof BABYLON.Condition && condition !== null) {
  48515. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  48516. if (action)
  48517. action.then(nothing);
  48518. else
  48519. actionManager.registerAction(nothing);
  48520. action = nothing;
  48521. }
  48522. if (combineArray === null) {
  48523. if (newAction instanceof BABYLON.Condition) {
  48524. condition = newAction;
  48525. newAction = action;
  48526. }
  48527. else {
  48528. condition = null;
  48529. if (action)
  48530. action.then(newAction);
  48531. else
  48532. actionManager.registerAction(newAction);
  48533. }
  48534. }
  48535. else {
  48536. combineArray.push(newAction);
  48537. }
  48538. for (var i = 0; i < parsedAction.children.length; i++)
  48539. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  48540. };
  48541. // triggers
  48542. for (var i = 0; i < parsedActions.children.length; i++) {
  48543. var triggerParams;
  48544. var trigger = parsedActions.children[i];
  48545. if (trigger.properties.length > 0) {
  48546. var param = trigger.properties[0].value;
  48547. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  48548. if (value._meshId) {
  48549. value.mesh = scene.getMeshByID(value._meshId);
  48550. }
  48551. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  48552. }
  48553. else
  48554. triggerParams = ActionManager[trigger.name];
  48555. for (var j = 0; j < trigger.children.length; j++) {
  48556. if (!trigger.detached)
  48557. traverse(trigger.children[j], triggerParams, null, null);
  48558. }
  48559. }
  48560. };
  48561. ActionManager.GetTriggerName = function (trigger) {
  48562. switch (trigger) {
  48563. case 0: return "NothingTrigger";
  48564. case 1: return "OnPickTrigger";
  48565. case 2: return "OnLeftPickTrigger";
  48566. case 3: return "OnRightPickTrigger";
  48567. case 4: return "OnCenterPickTrigger";
  48568. case 5: return "OnPickDownTrigger";
  48569. case 6: return "OnPickUpTrigger";
  48570. case 7: return "OnLongPressTrigger";
  48571. case 8: return "OnPointerOverTrigger";
  48572. case 9: return "OnPointerOutTrigger";
  48573. case 10: return "OnEveryFrameTrigger";
  48574. case 11: return "OnIntersectionEnterTrigger";
  48575. case 12: return "OnIntersectionExitTrigger";
  48576. case 13: return "OnKeyDownTrigger";
  48577. case 14: return "OnKeyUpTrigger";
  48578. case 15: return "OnPickOutTrigger";
  48579. default: return "";
  48580. }
  48581. };
  48582. // Statics
  48583. ActionManager._NothingTrigger = 0;
  48584. ActionManager._OnPickTrigger = 1;
  48585. ActionManager._OnLeftPickTrigger = 2;
  48586. ActionManager._OnRightPickTrigger = 3;
  48587. ActionManager._OnCenterPickTrigger = 4;
  48588. ActionManager._OnPickDownTrigger = 5;
  48589. ActionManager._OnDoublePickTrigger = 6;
  48590. ActionManager._OnPickUpTrigger = 7;
  48591. ActionManager._OnLongPressTrigger = 8;
  48592. ActionManager._OnPointerOverTrigger = 9;
  48593. ActionManager._OnPointerOutTrigger = 10;
  48594. ActionManager._OnEveryFrameTrigger = 11;
  48595. ActionManager._OnIntersectionEnterTrigger = 12;
  48596. ActionManager._OnIntersectionExitTrigger = 13;
  48597. ActionManager._OnKeyDownTrigger = 14;
  48598. ActionManager._OnKeyUpTrigger = 15;
  48599. ActionManager._OnPickOutTrigger = 16;
  48600. ActionManager.Triggers = {};
  48601. return ActionManager;
  48602. }());
  48603. BABYLON.ActionManager = ActionManager;
  48604. })(BABYLON || (BABYLON = {}));
  48605. //# sourceMappingURL=babylon.actionManager.js.map
  48606. var BABYLON;
  48607. (function (BABYLON) {
  48608. var InterpolateValueAction = /** @class */ (function (_super) {
  48609. __extends(InterpolateValueAction, _super);
  48610. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  48611. if (duration === void 0) { duration = 1000; }
  48612. var _this = _super.call(this, triggerOptions, condition) || this;
  48613. _this.propertyPath = propertyPath;
  48614. _this.value = value;
  48615. _this.duration = duration;
  48616. _this.stopOtherAnimations = stopOtherAnimations;
  48617. _this.onInterpolationDone = onInterpolationDone;
  48618. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  48619. _this._target = _this._effectiveTarget = target;
  48620. return _this;
  48621. }
  48622. InterpolateValueAction.prototype._prepare = function () {
  48623. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48624. this._property = this._getProperty(this.propertyPath);
  48625. };
  48626. InterpolateValueAction.prototype.execute = function () {
  48627. var _this = this;
  48628. var scene = this._actionManager.getScene();
  48629. var keys = [
  48630. {
  48631. frame: 0,
  48632. value: this._effectiveTarget[this._property]
  48633. }, {
  48634. frame: 100,
  48635. value: this.value
  48636. }
  48637. ];
  48638. var dataType;
  48639. if (typeof this.value === "number") {
  48640. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  48641. }
  48642. else if (this.value instanceof BABYLON.Color3) {
  48643. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  48644. }
  48645. else if (this.value instanceof BABYLON.Vector3) {
  48646. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  48647. }
  48648. else if (this.value instanceof BABYLON.Matrix) {
  48649. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  48650. }
  48651. else if (this.value instanceof BABYLON.Quaternion) {
  48652. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  48653. }
  48654. else {
  48655. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  48656. return;
  48657. }
  48658. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  48659. animation.setKeys(keys);
  48660. if (this.stopOtherAnimations) {
  48661. scene.stopAnimation(this._effectiveTarget);
  48662. }
  48663. var wrapper = function () {
  48664. _this.onInterpolationDoneObservable.notifyObservers(_this);
  48665. if (_this.onInterpolationDone) {
  48666. _this.onInterpolationDone();
  48667. }
  48668. };
  48669. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  48670. };
  48671. InterpolateValueAction.prototype.serialize = function (parent) {
  48672. return _super.prototype._serialize.call(this, {
  48673. name: "InterpolateValueAction",
  48674. properties: [
  48675. BABYLON.Action._GetTargetProperty(this._target),
  48676. { name: "propertyPath", value: this.propertyPath },
  48677. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48678. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  48679. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  48680. ]
  48681. }, parent);
  48682. };
  48683. return InterpolateValueAction;
  48684. }(BABYLON.Action));
  48685. BABYLON.InterpolateValueAction = InterpolateValueAction;
  48686. })(BABYLON || (BABYLON = {}));
  48687. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  48688. var BABYLON;
  48689. (function (BABYLON) {
  48690. var SwitchBooleanAction = /** @class */ (function (_super) {
  48691. __extends(SwitchBooleanAction, _super);
  48692. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  48693. var _this = _super.call(this, triggerOptions, condition) || this;
  48694. _this.propertyPath = propertyPath;
  48695. _this._target = _this._effectiveTarget = target;
  48696. return _this;
  48697. }
  48698. SwitchBooleanAction.prototype._prepare = function () {
  48699. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48700. this._property = this._getProperty(this.propertyPath);
  48701. };
  48702. SwitchBooleanAction.prototype.execute = function () {
  48703. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  48704. };
  48705. SwitchBooleanAction.prototype.serialize = function (parent) {
  48706. return _super.prototype._serialize.call(this, {
  48707. name: "SwitchBooleanAction",
  48708. properties: [
  48709. BABYLON.Action._GetTargetProperty(this._target),
  48710. { name: "propertyPath", value: this.propertyPath }
  48711. ]
  48712. }, parent);
  48713. };
  48714. return SwitchBooleanAction;
  48715. }(BABYLON.Action));
  48716. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  48717. var SetStateAction = /** @class */ (function (_super) {
  48718. __extends(SetStateAction, _super);
  48719. function SetStateAction(triggerOptions, target, value, condition) {
  48720. var _this = _super.call(this, triggerOptions, condition) || this;
  48721. _this.value = value;
  48722. _this._target = target;
  48723. return _this;
  48724. }
  48725. SetStateAction.prototype.execute = function () {
  48726. this._target.state = this.value;
  48727. };
  48728. SetStateAction.prototype.serialize = function (parent) {
  48729. return _super.prototype._serialize.call(this, {
  48730. name: "SetStateAction",
  48731. properties: [
  48732. BABYLON.Action._GetTargetProperty(this._target),
  48733. { name: "value", value: this.value }
  48734. ]
  48735. }, parent);
  48736. };
  48737. return SetStateAction;
  48738. }(BABYLON.Action));
  48739. BABYLON.SetStateAction = SetStateAction;
  48740. var SetValueAction = /** @class */ (function (_super) {
  48741. __extends(SetValueAction, _super);
  48742. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  48743. var _this = _super.call(this, triggerOptions, condition) || this;
  48744. _this.propertyPath = propertyPath;
  48745. _this.value = value;
  48746. _this._target = _this._effectiveTarget = target;
  48747. return _this;
  48748. }
  48749. SetValueAction.prototype._prepare = function () {
  48750. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48751. this._property = this._getProperty(this.propertyPath);
  48752. };
  48753. SetValueAction.prototype.execute = function () {
  48754. this._effectiveTarget[this._property] = this.value;
  48755. if (this._target.markAsDirty) {
  48756. this._target.markAsDirty(this._property);
  48757. }
  48758. };
  48759. SetValueAction.prototype.serialize = function (parent) {
  48760. return _super.prototype._serialize.call(this, {
  48761. name: "SetValueAction",
  48762. properties: [
  48763. BABYLON.Action._GetTargetProperty(this._target),
  48764. { name: "propertyPath", value: this.propertyPath },
  48765. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48766. ]
  48767. }, parent);
  48768. };
  48769. return SetValueAction;
  48770. }(BABYLON.Action));
  48771. BABYLON.SetValueAction = SetValueAction;
  48772. var IncrementValueAction = /** @class */ (function (_super) {
  48773. __extends(IncrementValueAction, _super);
  48774. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  48775. var _this = _super.call(this, triggerOptions, condition) || this;
  48776. _this.propertyPath = propertyPath;
  48777. _this.value = value;
  48778. _this._target = _this._effectiveTarget = target;
  48779. return _this;
  48780. }
  48781. IncrementValueAction.prototype._prepare = function () {
  48782. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48783. this._property = this._getProperty(this.propertyPath);
  48784. if (typeof this._effectiveTarget[this._property] !== "number") {
  48785. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  48786. }
  48787. };
  48788. IncrementValueAction.prototype.execute = function () {
  48789. this._effectiveTarget[this._property] += this.value;
  48790. if (this._target.markAsDirty) {
  48791. this._target.markAsDirty(this._property);
  48792. }
  48793. };
  48794. IncrementValueAction.prototype.serialize = function (parent) {
  48795. return _super.prototype._serialize.call(this, {
  48796. name: "IncrementValueAction",
  48797. properties: [
  48798. BABYLON.Action._GetTargetProperty(this._target),
  48799. { name: "propertyPath", value: this.propertyPath },
  48800. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48801. ]
  48802. }, parent);
  48803. };
  48804. return IncrementValueAction;
  48805. }(BABYLON.Action));
  48806. BABYLON.IncrementValueAction = IncrementValueAction;
  48807. var PlayAnimationAction = /** @class */ (function (_super) {
  48808. __extends(PlayAnimationAction, _super);
  48809. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  48810. var _this = _super.call(this, triggerOptions, condition) || this;
  48811. _this.from = from;
  48812. _this.to = to;
  48813. _this.loop = loop;
  48814. _this._target = target;
  48815. return _this;
  48816. }
  48817. PlayAnimationAction.prototype._prepare = function () {
  48818. };
  48819. PlayAnimationAction.prototype.execute = function () {
  48820. var scene = this._actionManager.getScene();
  48821. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  48822. };
  48823. PlayAnimationAction.prototype.serialize = function (parent) {
  48824. return _super.prototype._serialize.call(this, {
  48825. name: "PlayAnimationAction",
  48826. properties: [
  48827. BABYLON.Action._GetTargetProperty(this._target),
  48828. { name: "from", value: String(this.from) },
  48829. { name: "to", value: String(this.to) },
  48830. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  48831. ]
  48832. }, parent);
  48833. };
  48834. return PlayAnimationAction;
  48835. }(BABYLON.Action));
  48836. BABYLON.PlayAnimationAction = PlayAnimationAction;
  48837. var StopAnimationAction = /** @class */ (function (_super) {
  48838. __extends(StopAnimationAction, _super);
  48839. function StopAnimationAction(triggerOptions, target, condition) {
  48840. var _this = _super.call(this, triggerOptions, condition) || this;
  48841. _this._target = target;
  48842. return _this;
  48843. }
  48844. StopAnimationAction.prototype._prepare = function () {
  48845. };
  48846. StopAnimationAction.prototype.execute = function () {
  48847. var scene = this._actionManager.getScene();
  48848. scene.stopAnimation(this._target);
  48849. };
  48850. StopAnimationAction.prototype.serialize = function (parent) {
  48851. return _super.prototype._serialize.call(this, {
  48852. name: "StopAnimationAction",
  48853. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  48854. }, parent);
  48855. };
  48856. return StopAnimationAction;
  48857. }(BABYLON.Action));
  48858. BABYLON.StopAnimationAction = StopAnimationAction;
  48859. var DoNothingAction = /** @class */ (function (_super) {
  48860. __extends(DoNothingAction, _super);
  48861. function DoNothingAction(triggerOptions, condition) {
  48862. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  48863. return _super.call(this, triggerOptions, condition) || this;
  48864. }
  48865. DoNothingAction.prototype.execute = function () {
  48866. };
  48867. DoNothingAction.prototype.serialize = function (parent) {
  48868. return _super.prototype._serialize.call(this, {
  48869. name: "DoNothingAction",
  48870. properties: []
  48871. }, parent);
  48872. };
  48873. return DoNothingAction;
  48874. }(BABYLON.Action));
  48875. BABYLON.DoNothingAction = DoNothingAction;
  48876. var CombineAction = /** @class */ (function (_super) {
  48877. __extends(CombineAction, _super);
  48878. function CombineAction(triggerOptions, children, condition) {
  48879. var _this = _super.call(this, triggerOptions, condition) || this;
  48880. _this.children = children;
  48881. return _this;
  48882. }
  48883. CombineAction.prototype._prepare = function () {
  48884. for (var index = 0; index < this.children.length; index++) {
  48885. this.children[index]._actionManager = this._actionManager;
  48886. this.children[index]._prepare();
  48887. }
  48888. };
  48889. CombineAction.prototype.execute = function (evt) {
  48890. for (var index = 0; index < this.children.length; index++) {
  48891. this.children[index].execute(evt);
  48892. }
  48893. };
  48894. CombineAction.prototype.serialize = function (parent) {
  48895. var serializationObject = _super.prototype._serialize.call(this, {
  48896. name: "CombineAction",
  48897. properties: [],
  48898. combine: []
  48899. }, parent);
  48900. for (var i = 0; i < this.children.length; i++) {
  48901. serializationObject.combine.push(this.children[i].serialize(null));
  48902. }
  48903. return serializationObject;
  48904. };
  48905. return CombineAction;
  48906. }(BABYLON.Action));
  48907. BABYLON.CombineAction = CombineAction;
  48908. var ExecuteCodeAction = /** @class */ (function (_super) {
  48909. __extends(ExecuteCodeAction, _super);
  48910. function ExecuteCodeAction(triggerOptions, func, condition) {
  48911. var _this = _super.call(this, triggerOptions, condition) || this;
  48912. _this.func = func;
  48913. return _this;
  48914. }
  48915. ExecuteCodeAction.prototype.execute = function (evt) {
  48916. this.func(evt);
  48917. };
  48918. return ExecuteCodeAction;
  48919. }(BABYLON.Action));
  48920. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  48921. var SetParentAction = /** @class */ (function (_super) {
  48922. __extends(SetParentAction, _super);
  48923. function SetParentAction(triggerOptions, target, parent, condition) {
  48924. var _this = _super.call(this, triggerOptions, condition) || this;
  48925. _this._target = target;
  48926. _this._parent = parent;
  48927. return _this;
  48928. }
  48929. SetParentAction.prototype._prepare = function () {
  48930. };
  48931. SetParentAction.prototype.execute = function () {
  48932. if (this._target.parent === this._parent) {
  48933. return;
  48934. }
  48935. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  48936. invertParentWorldMatrix.invert();
  48937. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  48938. this._target.parent = this._parent;
  48939. };
  48940. SetParentAction.prototype.serialize = function (parent) {
  48941. return _super.prototype._serialize.call(this, {
  48942. name: "SetParentAction",
  48943. properties: [
  48944. BABYLON.Action._GetTargetProperty(this._target),
  48945. BABYLON.Action._GetTargetProperty(this._parent),
  48946. ]
  48947. }, parent);
  48948. };
  48949. return SetParentAction;
  48950. }(BABYLON.Action));
  48951. BABYLON.SetParentAction = SetParentAction;
  48952. var PlaySoundAction = /** @class */ (function (_super) {
  48953. __extends(PlaySoundAction, _super);
  48954. function PlaySoundAction(triggerOptions, sound, condition) {
  48955. var _this = _super.call(this, triggerOptions, condition) || this;
  48956. _this._sound = sound;
  48957. return _this;
  48958. }
  48959. PlaySoundAction.prototype._prepare = function () {
  48960. };
  48961. PlaySoundAction.prototype.execute = function () {
  48962. if (this._sound !== undefined)
  48963. this._sound.play();
  48964. };
  48965. PlaySoundAction.prototype.serialize = function (parent) {
  48966. return _super.prototype._serialize.call(this, {
  48967. name: "PlaySoundAction",
  48968. properties: [{ name: "sound", value: this._sound.name }]
  48969. }, parent);
  48970. };
  48971. return PlaySoundAction;
  48972. }(BABYLON.Action));
  48973. BABYLON.PlaySoundAction = PlaySoundAction;
  48974. var StopSoundAction = /** @class */ (function (_super) {
  48975. __extends(StopSoundAction, _super);
  48976. function StopSoundAction(triggerOptions, sound, condition) {
  48977. var _this = _super.call(this, triggerOptions, condition) || this;
  48978. _this._sound = sound;
  48979. return _this;
  48980. }
  48981. StopSoundAction.prototype._prepare = function () {
  48982. };
  48983. StopSoundAction.prototype.execute = function () {
  48984. if (this._sound !== undefined)
  48985. this._sound.stop();
  48986. };
  48987. StopSoundAction.prototype.serialize = function (parent) {
  48988. return _super.prototype._serialize.call(this, {
  48989. name: "StopSoundAction",
  48990. properties: [{ name: "sound", value: this._sound.name }]
  48991. }, parent);
  48992. };
  48993. return StopSoundAction;
  48994. }(BABYLON.Action));
  48995. BABYLON.StopSoundAction = StopSoundAction;
  48996. })(BABYLON || (BABYLON = {}));
  48997. //# sourceMappingURL=babylon.directActions.js.map
  48998. var BABYLON;
  48999. (function (BABYLON) {
  49000. var SpriteManager = /** @class */ (function () {
  49001. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  49002. if (epsilon === void 0) { epsilon = 0.01; }
  49003. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49004. this.name = name;
  49005. this.sprites = new Array();
  49006. this.renderingGroupId = 0;
  49007. this.layerMask = 0x0FFFFFFF;
  49008. this.fogEnabled = true;
  49009. this.isPickable = false;
  49010. /**
  49011. * An event triggered when the manager is disposed.
  49012. * @type {BABYLON.Observable}
  49013. */
  49014. this.onDisposeObservable = new BABYLON.Observable();
  49015. this._vertexBuffers = {};
  49016. this._capacity = capacity;
  49017. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  49018. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49019. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49020. if (cellSize.width && cellSize.height) {
  49021. this.cellWidth = cellSize.width;
  49022. this.cellHeight = cellSize.height;
  49023. }
  49024. else if (cellSize !== undefined) {
  49025. this.cellWidth = cellSize;
  49026. this.cellHeight = cellSize;
  49027. }
  49028. else {
  49029. return;
  49030. }
  49031. this._epsilon = epsilon;
  49032. this._scene = scene;
  49033. this._scene.spriteManagers.push(this);
  49034. var indices = [];
  49035. var index = 0;
  49036. for (var count = 0; count < capacity; count++) {
  49037. indices.push(index);
  49038. indices.push(index + 1);
  49039. indices.push(index + 2);
  49040. indices.push(index);
  49041. indices.push(index + 2);
  49042. indices.push(index + 3);
  49043. index += 4;
  49044. }
  49045. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  49046. // VBO
  49047. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  49048. this._vertexData = new Float32Array(capacity * 16 * 4);
  49049. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  49050. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  49051. var options = this._buffer.createVertexBuffer("options", 4, 4);
  49052. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  49053. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  49054. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  49055. this._vertexBuffers["options"] = options;
  49056. this._vertexBuffers["cellInfo"] = cellInfo;
  49057. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  49058. // Effects
  49059. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  49060. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  49061. }
  49062. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  49063. set: function (callback) {
  49064. if (this._onDisposeObserver) {
  49065. this.onDisposeObservable.remove(this._onDisposeObserver);
  49066. }
  49067. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  49068. },
  49069. enumerable: true,
  49070. configurable: true
  49071. });
  49072. Object.defineProperty(SpriteManager.prototype, "texture", {
  49073. get: function () {
  49074. return this._spriteTexture;
  49075. },
  49076. set: function (value) {
  49077. this._spriteTexture = value;
  49078. },
  49079. enumerable: true,
  49080. configurable: true
  49081. });
  49082. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  49083. var arrayOffset = index * 16;
  49084. if (offsetX === 0)
  49085. offsetX = this._epsilon;
  49086. else if (offsetX === 1)
  49087. offsetX = 1 - this._epsilon;
  49088. if (offsetY === 0)
  49089. offsetY = this._epsilon;
  49090. else if (offsetY === 1)
  49091. offsetY = 1 - this._epsilon;
  49092. this._vertexData[arrayOffset] = sprite.position.x;
  49093. this._vertexData[arrayOffset + 1] = sprite.position.y;
  49094. this._vertexData[arrayOffset + 2] = sprite.position.z;
  49095. this._vertexData[arrayOffset + 3] = sprite.angle;
  49096. this._vertexData[arrayOffset + 4] = sprite.width;
  49097. this._vertexData[arrayOffset + 5] = sprite.height;
  49098. this._vertexData[arrayOffset + 6] = offsetX;
  49099. this._vertexData[arrayOffset + 7] = offsetY;
  49100. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  49101. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  49102. var offset = (sprite.cellIndex / rowSize) >> 0;
  49103. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  49104. this._vertexData[arrayOffset + 11] = offset;
  49105. // Color
  49106. this._vertexData[arrayOffset + 12] = sprite.color.r;
  49107. this._vertexData[arrayOffset + 13] = sprite.color.g;
  49108. this._vertexData[arrayOffset + 14] = sprite.color.b;
  49109. this._vertexData[arrayOffset + 15] = sprite.color.a;
  49110. };
  49111. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  49112. var count = Math.min(this._capacity, this.sprites.length);
  49113. var min = BABYLON.Vector3.Zero();
  49114. var max = BABYLON.Vector3.Zero();
  49115. var distance = Number.MAX_VALUE;
  49116. var currentSprite = null;
  49117. var cameraSpacePosition = BABYLON.Vector3.Zero();
  49118. var cameraView = camera.getViewMatrix();
  49119. for (var index = 0; index < count; index++) {
  49120. var sprite = this.sprites[index];
  49121. if (!sprite) {
  49122. continue;
  49123. }
  49124. if (predicate) {
  49125. if (!predicate(sprite)) {
  49126. continue;
  49127. }
  49128. }
  49129. else if (!sprite.isPickable) {
  49130. continue;
  49131. }
  49132. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  49133. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  49134. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  49135. if (ray.intersectsBoxMinMax(min, max)) {
  49136. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  49137. if (distance > currentDistance) {
  49138. distance = currentDistance;
  49139. currentSprite = sprite;
  49140. if (fastCheck) {
  49141. break;
  49142. }
  49143. }
  49144. }
  49145. }
  49146. if (currentSprite) {
  49147. var result = new BABYLON.PickingInfo();
  49148. result.hit = true;
  49149. result.pickedSprite = currentSprite;
  49150. result.distance = distance;
  49151. return result;
  49152. }
  49153. return null;
  49154. };
  49155. SpriteManager.prototype.render = function () {
  49156. // Check
  49157. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  49158. return;
  49159. var engine = this._scene.getEngine();
  49160. var baseSize = this._spriteTexture.getBaseSize();
  49161. // Sprites
  49162. var deltaTime = engine.getDeltaTime();
  49163. var max = Math.min(this._capacity, this.sprites.length);
  49164. var rowSize = baseSize.width / this.cellWidth;
  49165. var offset = 0;
  49166. for (var index = 0; index < max; index++) {
  49167. var sprite = this.sprites[index];
  49168. if (!sprite) {
  49169. continue;
  49170. }
  49171. sprite._animate(deltaTime);
  49172. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  49173. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  49174. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  49175. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  49176. }
  49177. this._buffer.update(this._vertexData);
  49178. // Render
  49179. var effect = this._effectBase;
  49180. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49181. effect = this._effectFog;
  49182. }
  49183. engine.enableEffect(effect);
  49184. var viewMatrix = this._scene.getViewMatrix();
  49185. effect.setTexture("diffuseSampler", this._spriteTexture);
  49186. effect.setMatrix("view", viewMatrix);
  49187. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  49188. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  49189. // Fog
  49190. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49191. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  49192. effect.setColor3("vFogColor", this._scene.fogColor);
  49193. }
  49194. // VBOs
  49195. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  49196. // Draw order
  49197. engine.setDepthFunctionToLessOrEqual();
  49198. effect.setBool("alphaTest", true);
  49199. engine.setColorWrite(false);
  49200. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49201. engine.setColorWrite(true);
  49202. effect.setBool("alphaTest", false);
  49203. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  49204. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49205. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  49206. };
  49207. SpriteManager.prototype.dispose = function () {
  49208. if (this._buffer) {
  49209. this._buffer.dispose();
  49210. this._buffer = null;
  49211. }
  49212. if (this._indexBuffer) {
  49213. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  49214. this._indexBuffer = null;
  49215. }
  49216. if (this._spriteTexture) {
  49217. this._spriteTexture.dispose();
  49218. this._spriteTexture = null;
  49219. }
  49220. // Remove from scene
  49221. var index = this._scene.spriteManagers.indexOf(this);
  49222. this._scene.spriteManagers.splice(index, 1);
  49223. // Callback
  49224. this.onDisposeObservable.notifyObservers(this);
  49225. this.onDisposeObservable.clear();
  49226. };
  49227. return SpriteManager;
  49228. }());
  49229. BABYLON.SpriteManager = SpriteManager;
  49230. })(BABYLON || (BABYLON = {}));
  49231. //# sourceMappingURL=babylon.spriteManager.js.map
  49232. var BABYLON;
  49233. (function (BABYLON) {
  49234. var Sprite = /** @class */ (function () {
  49235. function Sprite(name, manager) {
  49236. this.name = name;
  49237. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49238. this.width = 1.0;
  49239. this.height = 1.0;
  49240. this.angle = 0;
  49241. this.cellIndex = 0;
  49242. this.invertU = 0;
  49243. this.invertV = 0;
  49244. this.animations = new Array();
  49245. this.isPickable = false;
  49246. this._animationStarted = false;
  49247. this._loopAnimation = false;
  49248. this._fromIndex = 0;
  49249. this._toIndex = 0;
  49250. this._delay = 0;
  49251. this._direction = 1;
  49252. this._time = 0;
  49253. this._manager = manager;
  49254. this._manager.sprites.push(this);
  49255. this.position = BABYLON.Vector3.Zero();
  49256. }
  49257. Object.defineProperty(Sprite.prototype, "size", {
  49258. get: function () {
  49259. return this.width;
  49260. },
  49261. set: function (value) {
  49262. this.width = value;
  49263. this.height = value;
  49264. },
  49265. enumerable: true,
  49266. configurable: true
  49267. });
  49268. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  49269. this._fromIndex = from;
  49270. this._toIndex = to;
  49271. this._loopAnimation = loop;
  49272. this._delay = delay;
  49273. this._animationStarted = true;
  49274. this._direction = from < to ? 1 : -1;
  49275. this.cellIndex = from;
  49276. this._time = 0;
  49277. this._onAnimationEnd = onAnimationEnd;
  49278. };
  49279. Sprite.prototype.stopAnimation = function () {
  49280. this._animationStarted = false;
  49281. };
  49282. Sprite.prototype._animate = function (deltaTime) {
  49283. if (!this._animationStarted)
  49284. return;
  49285. this._time += deltaTime;
  49286. if (this._time > this._delay) {
  49287. this._time = this._time % this._delay;
  49288. this.cellIndex += this._direction;
  49289. if (this.cellIndex > this._toIndex) {
  49290. if (this._loopAnimation) {
  49291. this.cellIndex = this._fromIndex;
  49292. }
  49293. else {
  49294. this.cellIndex = this._toIndex;
  49295. this._animationStarted = false;
  49296. if (this._onAnimationEnd) {
  49297. this._onAnimationEnd();
  49298. }
  49299. if (this.disposeWhenFinishedAnimating) {
  49300. this.dispose();
  49301. }
  49302. }
  49303. }
  49304. }
  49305. };
  49306. Sprite.prototype.dispose = function () {
  49307. for (var i = 0; i < this._manager.sprites.length; i++) {
  49308. if (this._manager.sprites[i] == this) {
  49309. this._manager.sprites.splice(i, 1);
  49310. }
  49311. }
  49312. };
  49313. return Sprite;
  49314. }());
  49315. BABYLON.Sprite = Sprite;
  49316. })(BABYLON || (BABYLON = {}));
  49317. //# sourceMappingURL=babylon.sprite.js.map
  49318. var BABYLON;
  49319. (function (BABYLON) {
  49320. var IntersectionInfo = /** @class */ (function () {
  49321. function IntersectionInfo(bu, bv, distance) {
  49322. this.bu = bu;
  49323. this.bv = bv;
  49324. this.distance = distance;
  49325. this.faceId = 0;
  49326. this.subMeshId = 0;
  49327. }
  49328. return IntersectionInfo;
  49329. }());
  49330. BABYLON.IntersectionInfo = IntersectionInfo;
  49331. var PickingInfo = /** @class */ (function () {
  49332. function PickingInfo() {
  49333. this.hit = false;
  49334. this.distance = 0;
  49335. this.pickedPoint = null;
  49336. this.pickedMesh = null;
  49337. this.bu = 0;
  49338. this.bv = 0;
  49339. this.faceId = -1;
  49340. this.subMeshId = 0;
  49341. this.pickedSprite = null;
  49342. }
  49343. // Methods
  49344. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  49345. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  49346. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  49347. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  49348. return null;
  49349. }
  49350. var indices = this.pickedMesh.getIndices();
  49351. if (!indices) {
  49352. return null;
  49353. }
  49354. var result;
  49355. if (useVerticesNormals) {
  49356. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49357. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  49358. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  49359. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  49360. normal0 = normal0.scale(this.bu);
  49361. normal1 = normal1.scale(this.bv);
  49362. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  49363. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  49364. }
  49365. else {
  49366. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49367. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  49368. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  49369. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  49370. var p1p2 = vertex1.subtract(vertex2);
  49371. var p3p2 = vertex3.subtract(vertex2);
  49372. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  49373. }
  49374. if (useWorldCoordinates) {
  49375. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  49376. }
  49377. return BABYLON.Vector3.Normalize(result);
  49378. };
  49379. PickingInfo.prototype.getTextureCoordinates = function () {
  49380. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49381. return null;
  49382. }
  49383. var indices = this.pickedMesh.getIndices();
  49384. if (!indices) {
  49385. return null;
  49386. }
  49387. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49388. if (!uvs) {
  49389. return null;
  49390. }
  49391. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  49392. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  49393. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  49394. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  49395. uv1 = uv1.scale(this.bu);
  49396. uv2 = uv2.scale(this.bv);
  49397. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  49398. };
  49399. return PickingInfo;
  49400. }());
  49401. BABYLON.PickingInfo = PickingInfo;
  49402. })(BABYLON || (BABYLON = {}));
  49403. //# sourceMappingURL=babylon.pickingInfo.js.map
  49404. var BABYLON;
  49405. (function (BABYLON) {
  49406. var Ray = /** @class */ (function () {
  49407. function Ray(origin, direction, length) {
  49408. if (length === void 0) { length = Number.MAX_VALUE; }
  49409. this.origin = origin;
  49410. this.direction = direction;
  49411. this.length = length;
  49412. }
  49413. // Methods
  49414. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  49415. var d = 0.0;
  49416. var maxValue = Number.MAX_VALUE;
  49417. var inv;
  49418. var min;
  49419. var max;
  49420. var temp;
  49421. if (Math.abs(this.direction.x) < 0.0000001) {
  49422. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  49423. return false;
  49424. }
  49425. }
  49426. else {
  49427. inv = 1.0 / this.direction.x;
  49428. min = (minimum.x - this.origin.x) * inv;
  49429. max = (maximum.x - this.origin.x) * inv;
  49430. if (max === -Infinity) {
  49431. max = Infinity;
  49432. }
  49433. if (min > max) {
  49434. temp = min;
  49435. min = max;
  49436. max = temp;
  49437. }
  49438. d = Math.max(min, d);
  49439. maxValue = Math.min(max, maxValue);
  49440. if (d > maxValue) {
  49441. return false;
  49442. }
  49443. }
  49444. if (Math.abs(this.direction.y) < 0.0000001) {
  49445. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  49446. return false;
  49447. }
  49448. }
  49449. else {
  49450. inv = 1.0 / this.direction.y;
  49451. min = (minimum.y - this.origin.y) * inv;
  49452. max = (maximum.y - this.origin.y) * inv;
  49453. if (max === -Infinity) {
  49454. max = Infinity;
  49455. }
  49456. if (min > max) {
  49457. temp = min;
  49458. min = max;
  49459. max = temp;
  49460. }
  49461. d = Math.max(min, d);
  49462. maxValue = Math.min(max, maxValue);
  49463. if (d > maxValue) {
  49464. return false;
  49465. }
  49466. }
  49467. if (Math.abs(this.direction.z) < 0.0000001) {
  49468. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  49469. return false;
  49470. }
  49471. }
  49472. else {
  49473. inv = 1.0 / this.direction.z;
  49474. min = (minimum.z - this.origin.z) * inv;
  49475. max = (maximum.z - this.origin.z) * inv;
  49476. if (max === -Infinity) {
  49477. max = Infinity;
  49478. }
  49479. if (min > max) {
  49480. temp = min;
  49481. min = max;
  49482. max = temp;
  49483. }
  49484. d = Math.max(min, d);
  49485. maxValue = Math.min(max, maxValue);
  49486. if (d > maxValue) {
  49487. return false;
  49488. }
  49489. }
  49490. return true;
  49491. };
  49492. Ray.prototype.intersectsBox = function (box) {
  49493. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  49494. };
  49495. Ray.prototype.intersectsSphere = function (sphere) {
  49496. var x = sphere.center.x - this.origin.x;
  49497. var y = sphere.center.y - this.origin.y;
  49498. var z = sphere.center.z - this.origin.z;
  49499. var pyth = (x * x) + (y * y) + (z * z);
  49500. var rr = sphere.radius * sphere.radius;
  49501. if (pyth <= rr) {
  49502. return true;
  49503. }
  49504. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  49505. if (dot < 0.0) {
  49506. return false;
  49507. }
  49508. var temp = pyth - (dot * dot);
  49509. return temp <= rr;
  49510. };
  49511. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  49512. if (!this._edge1) {
  49513. this._edge1 = BABYLON.Vector3.Zero();
  49514. this._edge2 = BABYLON.Vector3.Zero();
  49515. this._pvec = BABYLON.Vector3.Zero();
  49516. this._tvec = BABYLON.Vector3.Zero();
  49517. this._qvec = BABYLON.Vector3.Zero();
  49518. }
  49519. vertex1.subtractToRef(vertex0, this._edge1);
  49520. vertex2.subtractToRef(vertex0, this._edge2);
  49521. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  49522. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  49523. if (det === 0) {
  49524. return null;
  49525. }
  49526. var invdet = 1 / det;
  49527. this.origin.subtractToRef(vertex0, this._tvec);
  49528. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  49529. if (bu < 0 || bu > 1.0) {
  49530. return null;
  49531. }
  49532. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  49533. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  49534. if (bv < 0 || bu + bv > 1.0) {
  49535. return null;
  49536. }
  49537. //check if the distance is longer than the predefined length.
  49538. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  49539. if (distance > this.length) {
  49540. return null;
  49541. }
  49542. return new BABYLON.IntersectionInfo(bu, bv, distance);
  49543. };
  49544. Ray.prototype.intersectsPlane = function (plane) {
  49545. var distance;
  49546. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  49547. if (Math.abs(result1) < 9.99999997475243E-07) {
  49548. return null;
  49549. }
  49550. else {
  49551. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  49552. distance = (-plane.d - result2) / result1;
  49553. if (distance < 0.0) {
  49554. if (distance < -9.99999997475243E-07) {
  49555. return null;
  49556. }
  49557. else {
  49558. return 0;
  49559. }
  49560. }
  49561. return distance;
  49562. }
  49563. };
  49564. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  49565. var tm = BABYLON.Tmp.Matrix[0];
  49566. mesh.getWorldMatrix().invertToRef(tm);
  49567. if (this._tmpRay) {
  49568. Ray.TransformToRef(this, tm, this._tmpRay);
  49569. }
  49570. else {
  49571. this._tmpRay = Ray.Transform(this, tm);
  49572. }
  49573. return mesh.intersects(this._tmpRay, fastCheck);
  49574. };
  49575. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  49576. if (results) {
  49577. results.length = 0;
  49578. }
  49579. else {
  49580. results = [];
  49581. }
  49582. for (var i = 0; i < meshes.length; i++) {
  49583. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  49584. if (pickInfo.hit) {
  49585. results.push(pickInfo);
  49586. }
  49587. }
  49588. results.sort(this._comparePickingInfo);
  49589. return results;
  49590. };
  49591. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  49592. if (pickingInfoA.distance < pickingInfoB.distance) {
  49593. return -1;
  49594. }
  49595. else if (pickingInfoA.distance > pickingInfoB.distance) {
  49596. return 1;
  49597. }
  49598. else {
  49599. return 0;
  49600. }
  49601. };
  49602. /**
  49603. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  49604. * @param sega the first point of the segment to test the intersection against
  49605. * @param segb the second point of the segment to test the intersection against
  49606. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  49607. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  49608. */
  49609. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  49610. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  49611. var u = segb.subtract(sega);
  49612. var v = rsegb.subtract(this.origin);
  49613. var w = sega.subtract(this.origin);
  49614. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  49615. var b = BABYLON.Vector3.Dot(u, v);
  49616. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  49617. var d = BABYLON.Vector3.Dot(u, w);
  49618. var e = BABYLON.Vector3.Dot(v, w);
  49619. var D = a * c - b * b; // always >= 0
  49620. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  49621. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  49622. // compute the line parameters of the two closest points
  49623. if (D < Ray.smallnum) {
  49624. sN = 0.0; // force using point P0 on segment S1
  49625. sD = 1.0; // to prevent possible division by 0.0 later
  49626. tN = e;
  49627. tD = c;
  49628. }
  49629. else {
  49630. sN = (b * e - c * d);
  49631. tN = (a * e - b * d);
  49632. if (sN < 0.0) {
  49633. sN = 0.0;
  49634. tN = e;
  49635. tD = c;
  49636. }
  49637. else if (sN > sD) {
  49638. sN = sD;
  49639. tN = e + b;
  49640. tD = c;
  49641. }
  49642. }
  49643. if (tN < 0.0) {
  49644. tN = 0.0;
  49645. // recompute sc for this edge
  49646. if (-d < 0.0) {
  49647. sN = 0.0;
  49648. }
  49649. else if (-d > a)
  49650. sN = sD;
  49651. else {
  49652. sN = -d;
  49653. sD = a;
  49654. }
  49655. }
  49656. else if (tN > tD) {
  49657. tN = tD;
  49658. // recompute sc for this edge
  49659. if ((-d + b) < 0.0) {
  49660. sN = 0;
  49661. }
  49662. else if ((-d + b) > a) {
  49663. sN = sD;
  49664. }
  49665. else {
  49666. sN = (-d + b);
  49667. sD = a;
  49668. }
  49669. }
  49670. // finally do the division to get sc and tc
  49671. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  49672. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  49673. // get the difference of the two closest points
  49674. var qtc = v.multiplyByFloats(tc, tc, tc);
  49675. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  49676. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  49677. if (isIntersected) {
  49678. return qtc.length();
  49679. }
  49680. return -1;
  49681. };
  49682. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49683. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  49684. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  49685. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  49686. this.direction.normalize();
  49687. return this;
  49688. };
  49689. // Statics
  49690. Ray.Zero = function () {
  49691. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  49692. };
  49693. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49694. var result = Ray.Zero();
  49695. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  49696. };
  49697. /**
  49698. * 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
  49699. * transformed to the given world matrix.
  49700. * @param origin The origin point
  49701. * @param end The end point
  49702. * @param world a matrix to transform the ray to. Default is the identity matrix.
  49703. */
  49704. Ray.CreateNewFromTo = function (origin, end, world) {
  49705. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  49706. var direction = end.subtract(origin);
  49707. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  49708. direction.normalize();
  49709. return Ray.Transform(new Ray(origin, direction, length), world);
  49710. };
  49711. Ray.Transform = function (ray, matrix) {
  49712. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  49713. Ray.TransformToRef(ray, matrix, result);
  49714. return result;
  49715. };
  49716. Ray.TransformToRef = function (ray, matrix, result) {
  49717. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  49718. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  49719. result.length = ray.length;
  49720. var dir = result.direction;
  49721. var len = dir.length();
  49722. if (!(len === 0 || len === 1)) {
  49723. var num = 1.0 / len;
  49724. dir.x *= num;
  49725. dir.y *= num;
  49726. dir.z *= num;
  49727. result.length *= len;
  49728. }
  49729. };
  49730. Ray.smallnum = 0.00000001;
  49731. Ray.rayl = 10e8;
  49732. return Ray;
  49733. }());
  49734. BABYLON.Ray = Ray;
  49735. })(BABYLON || (BABYLON = {}));
  49736. //# sourceMappingURL=babylon.ray.js.map
  49737. var BABYLON;
  49738. (function (BABYLON) {
  49739. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  49740. if (boxMin.x > sphereCenter.x + sphereRadius)
  49741. return false;
  49742. if (sphereCenter.x - sphereRadius > boxMax.x)
  49743. return false;
  49744. if (boxMin.y > sphereCenter.y + sphereRadius)
  49745. return false;
  49746. if (sphereCenter.y - sphereRadius > boxMax.y)
  49747. return false;
  49748. if (boxMin.z > sphereCenter.z + sphereRadius)
  49749. return false;
  49750. if (sphereCenter.z - sphereRadius > boxMax.z)
  49751. return false;
  49752. return true;
  49753. };
  49754. var getLowestRoot = (function () {
  49755. var result = { root: 0, found: false };
  49756. return function (a, b, c, maxR) {
  49757. result.root = 0;
  49758. result.found = false;
  49759. var determinant = b * b - 4.0 * a * c;
  49760. if (determinant < 0)
  49761. return result;
  49762. var sqrtD = Math.sqrt(determinant);
  49763. var r1 = (-b - sqrtD) / (2.0 * a);
  49764. var r2 = (-b + sqrtD) / (2.0 * a);
  49765. if (r1 > r2) {
  49766. var temp = r2;
  49767. r2 = r1;
  49768. r1 = temp;
  49769. }
  49770. if (r1 > 0 && r1 < maxR) {
  49771. result.root = r1;
  49772. result.found = true;
  49773. return result;
  49774. }
  49775. if (r2 > 0 && r2 < maxR) {
  49776. result.root = r2;
  49777. result.found = true;
  49778. return result;
  49779. }
  49780. return result;
  49781. };
  49782. })();
  49783. var Collider = /** @class */ (function () {
  49784. function Collider() {
  49785. this._collisionPoint = BABYLON.Vector3.Zero();
  49786. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  49787. this._tempVector = BABYLON.Vector3.Zero();
  49788. this._tempVector2 = BABYLON.Vector3.Zero();
  49789. this._tempVector3 = BABYLON.Vector3.Zero();
  49790. this._tempVector4 = BABYLON.Vector3.Zero();
  49791. this._edge = BABYLON.Vector3.Zero();
  49792. this._baseToVertex = BABYLON.Vector3.Zero();
  49793. this._destinationPoint = BABYLON.Vector3.Zero();
  49794. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  49795. this._displacementVector = BABYLON.Vector3.Zero();
  49796. this._radius = BABYLON.Vector3.One();
  49797. this._retry = 0;
  49798. this._basePointWorld = BABYLON.Vector3.Zero();
  49799. this._velocityWorld = BABYLON.Vector3.Zero();
  49800. this._normalizedVelocity = BABYLON.Vector3.Zero();
  49801. this._collisionMask = -1;
  49802. }
  49803. Object.defineProperty(Collider.prototype, "collisionMask", {
  49804. get: function () {
  49805. return this._collisionMask;
  49806. },
  49807. set: function (mask) {
  49808. this._collisionMask = !isNaN(mask) ? mask : -1;
  49809. },
  49810. enumerable: true,
  49811. configurable: true
  49812. });
  49813. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  49814. /**
  49815. * Gets the plane normal used to compute the sliding response (in local space)
  49816. */
  49817. get: function () {
  49818. return this._slidePlaneNormal;
  49819. },
  49820. enumerable: true,
  49821. configurable: true
  49822. });
  49823. // Methods
  49824. Collider.prototype._initialize = function (source, dir, e) {
  49825. this._velocity = dir;
  49826. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  49827. this._basePoint = source;
  49828. source.multiplyToRef(this._radius, this._basePointWorld);
  49829. dir.multiplyToRef(this._radius, this._velocityWorld);
  49830. this._velocityWorldLength = this._velocityWorld.length();
  49831. this._epsilon = e;
  49832. this.collisionFound = false;
  49833. };
  49834. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  49835. pa.subtractToRef(point, this._tempVector);
  49836. pb.subtractToRef(point, this._tempVector2);
  49837. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  49838. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49839. if (d < 0)
  49840. return false;
  49841. pc.subtractToRef(point, this._tempVector3);
  49842. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  49843. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49844. if (d < 0)
  49845. return false;
  49846. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  49847. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49848. return d >= 0;
  49849. };
  49850. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  49851. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  49852. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  49853. if (distance > this._velocityWorldLength + max + sphereRadius) {
  49854. return false;
  49855. }
  49856. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  49857. return false;
  49858. return true;
  49859. };
  49860. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  49861. var t0;
  49862. var embeddedInPlane = false;
  49863. //defensive programming, actually not needed.
  49864. if (!trianglePlaneArray) {
  49865. trianglePlaneArray = [];
  49866. }
  49867. if (!trianglePlaneArray[faceIndex]) {
  49868. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  49869. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  49870. }
  49871. var trianglePlane = trianglePlaneArray[faceIndex];
  49872. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  49873. return;
  49874. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  49875. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  49876. if (normalDotVelocity == 0) {
  49877. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  49878. return;
  49879. embeddedInPlane = true;
  49880. t0 = 0;
  49881. }
  49882. else {
  49883. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49884. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49885. if (t0 > t1) {
  49886. var temp = t1;
  49887. t1 = t0;
  49888. t0 = temp;
  49889. }
  49890. if (t0 > 1.0 || t1 < 0.0)
  49891. return;
  49892. if (t0 < 0)
  49893. t0 = 0;
  49894. if (t0 > 1.0)
  49895. t0 = 1.0;
  49896. }
  49897. this._collisionPoint.copyFromFloats(0, 0, 0);
  49898. var found = false;
  49899. var t = 1.0;
  49900. if (!embeddedInPlane) {
  49901. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  49902. this._velocity.scaleToRef(t0, this._tempVector);
  49903. this._planeIntersectionPoint.addInPlace(this._tempVector);
  49904. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  49905. found = true;
  49906. t = t0;
  49907. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  49908. }
  49909. }
  49910. if (!found) {
  49911. var velocitySquaredLength = this._velocity.lengthSquared();
  49912. var a = velocitySquaredLength;
  49913. this._basePoint.subtractToRef(p1, this._tempVector);
  49914. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49915. var c = this._tempVector.lengthSquared() - 1.0;
  49916. var lowestRoot = getLowestRoot(a, b, c, t);
  49917. if (lowestRoot.found) {
  49918. t = lowestRoot.root;
  49919. found = true;
  49920. this._collisionPoint.copyFrom(p1);
  49921. }
  49922. this._basePoint.subtractToRef(p2, this._tempVector);
  49923. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49924. c = this._tempVector.lengthSquared() - 1.0;
  49925. lowestRoot = getLowestRoot(a, b, c, t);
  49926. if (lowestRoot.found) {
  49927. t = lowestRoot.root;
  49928. found = true;
  49929. this._collisionPoint.copyFrom(p2);
  49930. }
  49931. this._basePoint.subtractToRef(p3, this._tempVector);
  49932. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49933. c = this._tempVector.lengthSquared() - 1.0;
  49934. lowestRoot = getLowestRoot(a, b, c, t);
  49935. if (lowestRoot.found) {
  49936. t = lowestRoot.root;
  49937. found = true;
  49938. this._collisionPoint.copyFrom(p3);
  49939. }
  49940. p2.subtractToRef(p1, this._edge);
  49941. p1.subtractToRef(this._basePoint, this._baseToVertex);
  49942. var edgeSquaredLength = this._edge.lengthSquared();
  49943. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49944. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49945. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49946. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49947. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49948. lowestRoot = getLowestRoot(a, b, c, t);
  49949. if (lowestRoot.found) {
  49950. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49951. if (f >= 0.0 && f <= 1.0) {
  49952. t = lowestRoot.root;
  49953. found = true;
  49954. this._edge.scaleInPlace(f);
  49955. p1.addToRef(this._edge, this._collisionPoint);
  49956. }
  49957. }
  49958. p3.subtractToRef(p2, this._edge);
  49959. p2.subtractToRef(this._basePoint, this._baseToVertex);
  49960. edgeSquaredLength = this._edge.lengthSquared();
  49961. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49962. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49963. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49964. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49965. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49966. lowestRoot = getLowestRoot(a, b, c, t);
  49967. if (lowestRoot.found) {
  49968. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49969. if (f >= 0.0 && f <= 1.0) {
  49970. t = lowestRoot.root;
  49971. found = true;
  49972. this._edge.scaleInPlace(f);
  49973. p2.addToRef(this._edge, this._collisionPoint);
  49974. }
  49975. }
  49976. p1.subtractToRef(p3, this._edge);
  49977. p3.subtractToRef(this._basePoint, this._baseToVertex);
  49978. edgeSquaredLength = this._edge.lengthSquared();
  49979. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49980. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49981. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49982. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49983. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49984. lowestRoot = getLowestRoot(a, b, c, t);
  49985. if (lowestRoot.found) {
  49986. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49987. if (f >= 0.0 && f <= 1.0) {
  49988. t = lowestRoot.root;
  49989. found = true;
  49990. this._edge.scaleInPlace(f);
  49991. p3.addToRef(this._edge, this._collisionPoint);
  49992. }
  49993. }
  49994. }
  49995. if (found) {
  49996. var distToCollision = t * this._velocity.length();
  49997. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  49998. if (!this.intersectionPoint) {
  49999. this.intersectionPoint = this._collisionPoint.clone();
  50000. }
  50001. else {
  50002. this.intersectionPoint.copyFrom(this._collisionPoint);
  50003. }
  50004. this._nearestDistance = distToCollision;
  50005. this.collisionFound = true;
  50006. }
  50007. }
  50008. };
  50009. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  50010. for (var i = indexStart; i < indexEnd; i += 3) {
  50011. var p1 = pts[indices[i] - decal];
  50012. var p2 = pts[indices[i + 1] - decal];
  50013. var p3 = pts[indices[i + 2] - decal];
  50014. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  50015. }
  50016. };
  50017. Collider.prototype._getResponse = function (pos, vel) {
  50018. pos.addToRef(vel, this._destinationPoint);
  50019. vel.scaleInPlace((this._nearestDistance / vel.length()));
  50020. this._basePoint.addToRef(vel, pos);
  50021. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  50022. this._slidePlaneNormal.normalize();
  50023. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  50024. pos.addInPlace(this._displacementVector);
  50025. this.intersectionPoint.addInPlace(this._displacementVector);
  50026. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  50027. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  50028. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  50029. };
  50030. return Collider;
  50031. }());
  50032. BABYLON.Collider = Collider;
  50033. })(BABYLON || (BABYLON = {}));
  50034. //# sourceMappingURL=babylon.collider.js.map
  50035. var BABYLON;
  50036. (function (BABYLON) {
  50037. //WebWorker code will be inserted to this variable.
  50038. BABYLON.CollisionWorker = "";
  50039. var WorkerTaskType;
  50040. (function (WorkerTaskType) {
  50041. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  50042. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  50043. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  50044. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  50045. var WorkerReplyType;
  50046. (function (WorkerReplyType) {
  50047. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  50048. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  50049. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  50050. var CollisionCoordinatorWorker = /** @class */ (function () {
  50051. function CollisionCoordinatorWorker() {
  50052. var _this = this;
  50053. this._scaledPosition = BABYLON.Vector3.Zero();
  50054. this._scaledVelocity = BABYLON.Vector3.Zero();
  50055. this.onMeshUpdated = function (transformNode) {
  50056. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  50057. };
  50058. this.onGeometryUpdated = function (geometry) {
  50059. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  50060. };
  50061. this._afterRender = function () {
  50062. if (!_this._init)
  50063. return;
  50064. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  50065. return;
  50066. }
  50067. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  50068. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  50069. if (_this._runningUpdated > 4) {
  50070. return;
  50071. }
  50072. ++_this._runningUpdated;
  50073. var payload = {
  50074. updatedMeshes: _this._addUpdateMeshesList,
  50075. updatedGeometries: _this._addUpdateGeometriesList,
  50076. removedGeometries: _this._toRemoveGeometryArray,
  50077. removedMeshes: _this._toRemoveMeshesArray
  50078. };
  50079. var message = {
  50080. payload: payload,
  50081. taskType: WorkerTaskType.UPDATE
  50082. };
  50083. var serializable = [];
  50084. for (var id in payload.updatedGeometries) {
  50085. if (payload.updatedGeometries.hasOwnProperty(id)) {
  50086. //prepare transferables
  50087. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  50088. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  50089. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  50090. }
  50091. }
  50092. _this._worker.postMessage(message, serializable);
  50093. _this._addUpdateMeshesList = {};
  50094. _this._addUpdateGeometriesList = {};
  50095. _this._toRemoveGeometryArray = [];
  50096. _this._toRemoveMeshesArray = [];
  50097. };
  50098. this._onMessageFromWorker = function (e) {
  50099. var returnData = e.data;
  50100. if (returnData.error != WorkerReplyType.SUCCESS) {
  50101. //TODO what errors can be returned from the worker?
  50102. BABYLON.Tools.Warn("error returned from worker!");
  50103. return;
  50104. }
  50105. switch (returnData.taskType) {
  50106. case WorkerTaskType.INIT:
  50107. _this._init = true;
  50108. //Update the worked with ALL of the scene's current state
  50109. _this._scene.meshes.forEach(function (mesh) {
  50110. _this.onMeshAdded(mesh);
  50111. });
  50112. _this._scene.getGeometries().forEach(function (geometry) {
  50113. _this.onGeometryAdded(geometry);
  50114. });
  50115. break;
  50116. case WorkerTaskType.UPDATE:
  50117. _this._runningUpdated--;
  50118. break;
  50119. case WorkerTaskType.COLLIDE:
  50120. var returnPayload = returnData.payload;
  50121. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  50122. return;
  50123. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  50124. if (callback) {
  50125. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  50126. if (mesh) {
  50127. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  50128. }
  50129. }
  50130. //cleanup
  50131. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  50132. break;
  50133. }
  50134. };
  50135. this._collisionsCallbackArray = [];
  50136. this._init = false;
  50137. this._runningUpdated = 0;
  50138. this._addUpdateMeshesList = {};
  50139. this._addUpdateGeometriesList = {};
  50140. this._toRemoveGeometryArray = [];
  50141. this._toRemoveMeshesArray = [];
  50142. }
  50143. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50144. if (!this._init)
  50145. return;
  50146. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  50147. return;
  50148. position.divideToRef(collider._radius, this._scaledPosition);
  50149. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50150. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  50151. var payload = {
  50152. collider: {
  50153. position: this._scaledPosition.asArray(),
  50154. velocity: this._scaledVelocity.asArray(),
  50155. radius: collider._radius.asArray()
  50156. },
  50157. collisionId: collisionIndex,
  50158. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  50159. maximumRetry: maximumRetry
  50160. };
  50161. var message = {
  50162. payload: payload,
  50163. taskType: WorkerTaskType.COLLIDE
  50164. };
  50165. this._worker.postMessage(message);
  50166. };
  50167. CollisionCoordinatorWorker.prototype.init = function (scene) {
  50168. this._scene = scene;
  50169. this._scene.registerAfterRender(this._afterRender);
  50170. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  50171. this._worker = new Worker(workerUrl);
  50172. this._worker.onmessage = this._onMessageFromWorker;
  50173. var message = {
  50174. payload: {},
  50175. taskType: WorkerTaskType.INIT
  50176. };
  50177. this._worker.postMessage(message);
  50178. };
  50179. CollisionCoordinatorWorker.prototype.destroy = function () {
  50180. this._scene.unregisterAfterRender(this._afterRender);
  50181. this._worker.terminate();
  50182. };
  50183. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  50184. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  50185. this.onMeshUpdated(mesh);
  50186. };
  50187. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  50188. this._toRemoveMeshesArray.push(mesh.uniqueId);
  50189. };
  50190. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  50191. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  50192. geometry.onGeometryUpdated = this.onGeometryUpdated;
  50193. this.onGeometryUpdated(geometry);
  50194. };
  50195. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  50196. this._toRemoveGeometryArray.push(geometry.id);
  50197. };
  50198. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  50199. var submeshes = [];
  50200. if (mesh.subMeshes) {
  50201. submeshes = mesh.subMeshes.map(function (sm, idx) {
  50202. var boundingInfo = sm.getBoundingInfo();
  50203. return {
  50204. position: idx,
  50205. verticesStart: sm.verticesStart,
  50206. verticesCount: sm.verticesCount,
  50207. indexStart: sm.indexStart,
  50208. indexCount: sm.indexCount,
  50209. hasMaterial: !!sm.getMaterial(),
  50210. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50211. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50212. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50213. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  50214. };
  50215. });
  50216. }
  50217. var geometryId = null;
  50218. if (mesh instanceof BABYLON.Mesh) {
  50219. var geometry = mesh.geometry;
  50220. geometryId = geometry ? geometry.id : null;
  50221. }
  50222. else if (mesh instanceof BABYLON.InstancedMesh) {
  50223. var geometry = mesh.sourceMesh.geometry;
  50224. geometryId = geometry ? geometry.id : null;
  50225. }
  50226. var boundingInfo = mesh.getBoundingInfo();
  50227. return {
  50228. uniqueId: mesh.uniqueId,
  50229. id: mesh.id,
  50230. name: mesh.name,
  50231. geometryId: geometryId,
  50232. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50233. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50234. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50235. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  50236. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  50237. subMeshes: submeshes,
  50238. checkCollisions: mesh.checkCollisions
  50239. };
  50240. };
  50241. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  50242. return {
  50243. id: geometry.id,
  50244. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  50245. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  50246. indices: new Uint32Array(geometry.getIndices() || []),
  50247. };
  50248. };
  50249. return CollisionCoordinatorWorker;
  50250. }());
  50251. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  50252. var CollisionCoordinatorLegacy = /** @class */ (function () {
  50253. function CollisionCoordinatorLegacy() {
  50254. this._scaledPosition = BABYLON.Vector3.Zero();
  50255. this._scaledVelocity = BABYLON.Vector3.Zero();
  50256. this._finalPosition = BABYLON.Vector3.Zero();
  50257. }
  50258. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50259. position.divideToRef(collider._radius, this._scaledPosition);
  50260. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50261. collider.collidedMesh = null;
  50262. collider._retry = 0;
  50263. collider._initialVelocity = this._scaledVelocity;
  50264. collider._initialPosition = this._scaledPosition;
  50265. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  50266. this._finalPosition.multiplyInPlace(collider._radius);
  50267. //run the callback
  50268. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  50269. };
  50270. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  50271. this._scene = scene;
  50272. };
  50273. CollisionCoordinatorLegacy.prototype.destroy = function () {
  50274. //Legacy need no destruction method.
  50275. };
  50276. //No update in legacy mode
  50277. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  50278. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  50279. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  50280. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  50281. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  50282. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  50283. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  50284. if (excludedMesh === void 0) { excludedMesh = null; }
  50285. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  50286. if (collider._retry >= maximumRetry) {
  50287. finalPosition.copyFrom(position);
  50288. return;
  50289. }
  50290. // Check if this is a mesh else camera or -1
  50291. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  50292. collider._initialize(position, velocity, closeDistance);
  50293. // Check all meshes
  50294. for (var index = 0; index < this._scene.meshes.length; index++) {
  50295. var mesh = this._scene.meshes[index];
  50296. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  50297. mesh._checkCollision(collider);
  50298. }
  50299. }
  50300. if (!collider.collisionFound) {
  50301. position.addToRef(velocity, finalPosition);
  50302. return;
  50303. }
  50304. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  50305. collider._getResponse(position, velocity);
  50306. }
  50307. if (velocity.length() <= closeDistance) {
  50308. finalPosition.copyFrom(position);
  50309. return;
  50310. }
  50311. collider._retry++;
  50312. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  50313. };
  50314. return CollisionCoordinatorLegacy;
  50315. }());
  50316. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  50317. })(BABYLON || (BABYLON = {}));
  50318. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  50319. var BABYLON;
  50320. (function (BABYLON) {
  50321. /**
  50322. * A particle represents one of the element emitted by a particle system.
  50323. * This is mainly define by its coordinates, direction, velocity and age.
  50324. */
  50325. var Particle = /** @class */ (function () {
  50326. /**
  50327. * Creates a new instance of @see Particle
  50328. * @param particleSystem the particle system the particle belongs to
  50329. */
  50330. function Particle(particleSystem) {
  50331. this.particleSystem = particleSystem;
  50332. /**
  50333. * The world position of the particle in the scene.
  50334. */
  50335. this.position = BABYLON.Vector3.Zero();
  50336. /**
  50337. * The world direction of the particle in the scene.
  50338. */
  50339. this.direction = BABYLON.Vector3.Zero();
  50340. /**
  50341. * The color of the particle.
  50342. */
  50343. this.color = new BABYLON.Color4(0, 0, 0, 0);
  50344. /**
  50345. * The color change of the particle per step.
  50346. */
  50347. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  50348. /**
  50349. * Defines how long will the life of the particle be.
  50350. */
  50351. this.lifeTime = 1.0;
  50352. /**
  50353. * The current age of the particle.
  50354. */
  50355. this.age = 0;
  50356. /**
  50357. * The current size of the particle.
  50358. */
  50359. this.size = 0;
  50360. /**
  50361. * The current angle of the particle.
  50362. */
  50363. this.angle = 0;
  50364. /**
  50365. * Defines how fast is the angle changing.
  50366. */
  50367. this.angularSpeed = 0;
  50368. /**
  50369. * Defines the cell index used by the particle to be rendered from a sprite.
  50370. */
  50371. this.cellIndex = 0;
  50372. this._currentFrameCounter = 0;
  50373. if (!this.particleSystem.isAnimationSheetEnabled) {
  50374. return;
  50375. }
  50376. this.cellIndex = this.particleSystem.startSpriteCellID;
  50377. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  50378. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  50379. }
  50380. else {
  50381. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  50382. }
  50383. }
  50384. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  50385. // (ageOffset / scaledUpdateSpeed) / available cells
  50386. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  50387. this._currentFrameCounter += scaledUpdateSpeed;
  50388. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  50389. this._currentFrameCounter = 0;
  50390. this.cellIndex++;
  50391. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50392. this.cellIndex = this.particleSystem.endSpriteCellID;
  50393. }
  50394. }
  50395. };
  50396. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  50397. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  50398. this.cellIndex++;
  50399. this._currentFrameCounter = 0;
  50400. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50401. if (this.particleSystem.spriteCellLoop) {
  50402. this.cellIndex = this.particleSystem.startSpriteCellID;
  50403. }
  50404. else {
  50405. this.cellIndex = this.particleSystem.endSpriteCellID;
  50406. }
  50407. }
  50408. }
  50409. else {
  50410. this._currentFrameCounter++;
  50411. }
  50412. };
  50413. /**
  50414. * Copy the properties of particle to another one.
  50415. * @param other the particle to copy the information to.
  50416. */
  50417. Particle.prototype.copyTo = function (other) {
  50418. other.position.copyFrom(this.position);
  50419. other.direction.copyFrom(this.direction);
  50420. other.color.copyFrom(this.color);
  50421. other.colorStep.copyFrom(this.colorStep);
  50422. other.lifeTime = this.lifeTime;
  50423. other.age = this.age;
  50424. other.size = this.size;
  50425. other.angle = this.angle;
  50426. other.angularSpeed = this.angularSpeed;
  50427. other.particleSystem = this.particleSystem;
  50428. other.cellIndex = this.cellIndex;
  50429. };
  50430. return Particle;
  50431. }());
  50432. BABYLON.Particle = Particle;
  50433. })(BABYLON || (BABYLON = {}));
  50434. //# sourceMappingURL=babylon.particle.js.map
  50435. var BABYLON;
  50436. (function (BABYLON) {
  50437. /**
  50438. * This represents a particle system in Babylon.
  50439. * 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.
  50440. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  50441. * @example https://doc.babylonjs.com/babylon101/particles
  50442. */
  50443. var ParticleSystem = /** @class */ (function () {
  50444. /**
  50445. * Instantiates a particle system.
  50446. * 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.
  50447. * @param name The name of the particle system
  50448. * @param capacity The max number of particles alive at the same time
  50449. * @param scene The scene the particle system belongs to
  50450. * @param customEffect a custom effect used to change the way particles are rendered by default
  50451. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  50452. * @param epsilon Offset used to render the particles
  50453. */
  50454. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  50455. if (customEffect === void 0) { customEffect = null; }
  50456. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  50457. if (epsilon === void 0) { epsilon = 0.01; }
  50458. var _this = this;
  50459. /**
  50460. * List of animations used by the particle system.
  50461. */
  50462. this.animations = [];
  50463. /**
  50464. * The rendering group used by the Particle system to chose when to render.
  50465. */
  50466. this.renderingGroupId = 0;
  50467. /**
  50468. * The emitter represents the Mesh or position we are attaching the particle system to.
  50469. */
  50470. this.emitter = null;
  50471. /**
  50472. * The maximum number of particles to emit per frame
  50473. */
  50474. this.emitRate = 10;
  50475. /**
  50476. * If you want to launch only a few particles at once, that can be done, as well.
  50477. */
  50478. this.manualEmitCount = -1;
  50479. /**
  50480. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  50481. */
  50482. this.updateSpeed = 0.01;
  50483. /**
  50484. * The amount of time the particle system is running (depends of the overall update speed).
  50485. */
  50486. this.targetStopDuration = 0;
  50487. /**
  50488. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  50489. */
  50490. this.disposeOnStop = false;
  50491. /**
  50492. * Minimum power of emitting particles.
  50493. */
  50494. this.minEmitPower = 1;
  50495. /**
  50496. * Maximum power of emitting particles.
  50497. */
  50498. this.maxEmitPower = 1;
  50499. /**
  50500. * Minimum life time of emitting particles.
  50501. */
  50502. this.minLifeTime = 1;
  50503. /**
  50504. * Maximum life time of emitting particles.
  50505. */
  50506. this.maxLifeTime = 1;
  50507. /**
  50508. * Minimum Size of emitting particles.
  50509. */
  50510. this.minSize = 1;
  50511. /**
  50512. * Maximum Size of emitting particles.
  50513. */
  50514. this.maxSize = 1;
  50515. /**
  50516. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  50517. */
  50518. this.minAngularSpeed = 0;
  50519. /**
  50520. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  50521. */
  50522. this.maxAngularSpeed = 0;
  50523. /**
  50524. * The layer mask we are rendering the particles through.
  50525. */
  50526. this.layerMask = 0x0FFFFFFF;
  50527. /**
  50528. * This can help using your own shader to render the particle system.
  50529. * The according effect will be created
  50530. */
  50531. this.customShader = null;
  50532. /**
  50533. * By default particle system starts as soon as they are created. This prevents the
  50534. * automatic start to happen and let you decide when to start emitting particles.
  50535. */
  50536. this.preventAutoStart = false;
  50537. /**
  50538. * Callback triggered when the particle animation is ending.
  50539. */
  50540. this.onAnimationEnd = null;
  50541. /**
  50542. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  50543. */
  50544. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  50545. /**
  50546. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  50547. * to override the particles.
  50548. */
  50549. this.forceDepthWrite = false;
  50550. /**
  50551. * You can use gravity if you want to give an orientation to your particles.
  50552. */
  50553. this.gravity = BABYLON.Vector3.Zero();
  50554. /**
  50555. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50556. */
  50557. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50558. /**
  50559. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50560. */
  50561. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50562. /**
  50563. * Color the particle will have at the end of its lifetime.
  50564. */
  50565. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  50566. /**
  50567. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  50568. */
  50569. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50570. /**
  50571. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  50572. */
  50573. this.spriteCellLoop = true;
  50574. /**
  50575. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  50576. */
  50577. this.spriteCellChangeSpeed = 0;
  50578. /**
  50579. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  50580. */
  50581. this.startSpriteCellID = 0;
  50582. /**
  50583. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  50584. */
  50585. this.endSpriteCellID = 0;
  50586. /**
  50587. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  50588. */
  50589. this.spriteCellWidth = 0;
  50590. /**
  50591. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  50592. */
  50593. this.spriteCellHeight = 0;
  50594. /**
  50595. * An event triggered when the system is disposed.
  50596. */
  50597. this.onDisposeObservable = new BABYLON.Observable();
  50598. this._particles = new Array();
  50599. this._stockParticles = new Array();
  50600. this._newPartsExcess = 0;
  50601. this._vertexBuffers = {};
  50602. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  50603. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  50604. this._scaledDirection = BABYLON.Vector3.Zero();
  50605. this._scaledGravity = BABYLON.Vector3.Zero();
  50606. this._currentRenderId = -1;
  50607. this._started = false;
  50608. this._stopped = false;
  50609. this._actualFrame = 0;
  50610. this._vertexBufferSize = 11;
  50611. this._appendParticleVertexes = null;
  50612. this.id = name;
  50613. this.name = name;
  50614. this._capacity = capacity;
  50615. this._epsilon = epsilon;
  50616. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  50617. if (isAnimationSheetEnabled) {
  50618. this._vertexBufferSize = 12;
  50619. }
  50620. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50621. this._customEffect = customEffect;
  50622. scene.particleSystems.push(this);
  50623. this._createIndexBuffer();
  50624. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  50625. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  50626. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  50627. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  50628. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  50629. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  50630. if (this._isAnimationSheetEnabled) {
  50631. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  50632. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  50633. }
  50634. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50635. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50636. this._vertexBuffers["options"] = options;
  50637. // Default emitter type
  50638. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  50639. this.updateFunction = function (particles) {
  50640. for (var index = 0; index < particles.length; index++) {
  50641. var particle = particles[index];
  50642. particle.age += _this._scaledUpdateSpeed;
  50643. if (particle.age >= particle.lifeTime) {
  50644. _this.recycleParticle(particle);
  50645. index--;
  50646. continue;
  50647. }
  50648. else {
  50649. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  50650. particle.color.addInPlace(_this._scaledColorStep);
  50651. if (particle.color.a < 0)
  50652. particle.color.a = 0;
  50653. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  50654. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  50655. particle.position.addInPlace(_this._scaledDirection);
  50656. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  50657. particle.direction.addInPlace(_this._scaledGravity);
  50658. if (_this._isAnimationSheetEnabled) {
  50659. particle.updateCellIndex(_this._scaledUpdateSpeed);
  50660. }
  50661. }
  50662. }
  50663. };
  50664. }
  50665. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  50666. /**
  50667. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50668. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50669. */
  50670. get: function () {
  50671. if (this.particleEmitterType.direction1) {
  50672. return this.particleEmitterType.direction1;
  50673. }
  50674. return BABYLON.Vector3.Zero();
  50675. },
  50676. set: function (value) {
  50677. if (this.particleEmitterType.direction1) {
  50678. this.particleEmitterType.direction1 = value;
  50679. }
  50680. },
  50681. enumerable: true,
  50682. configurable: true
  50683. });
  50684. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  50685. /**
  50686. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50687. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50688. */
  50689. get: function () {
  50690. if (this.particleEmitterType.direction2) {
  50691. return this.particleEmitterType.direction2;
  50692. }
  50693. return BABYLON.Vector3.Zero();
  50694. },
  50695. set: function (value) {
  50696. if (this.particleEmitterType.direction2) {
  50697. this.particleEmitterType.direction2 = value;
  50698. }
  50699. },
  50700. enumerable: true,
  50701. configurable: true
  50702. });
  50703. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  50704. /**
  50705. * 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.
  50706. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50707. */
  50708. get: function () {
  50709. if (this.particleEmitterType.minEmitBox) {
  50710. return this.particleEmitterType.minEmitBox;
  50711. }
  50712. return BABYLON.Vector3.Zero();
  50713. },
  50714. set: function (value) {
  50715. if (this.particleEmitterType.minEmitBox) {
  50716. this.particleEmitterType.minEmitBox = value;
  50717. }
  50718. },
  50719. enumerable: true,
  50720. configurable: true
  50721. });
  50722. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  50723. /**
  50724. * 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.
  50725. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50726. */
  50727. get: function () {
  50728. if (this.particleEmitterType.maxEmitBox) {
  50729. return this.particleEmitterType.maxEmitBox;
  50730. }
  50731. return BABYLON.Vector3.Zero();
  50732. },
  50733. set: function (value) {
  50734. if (this.particleEmitterType.maxEmitBox) {
  50735. this.particleEmitterType.maxEmitBox = value;
  50736. }
  50737. },
  50738. enumerable: true,
  50739. configurable: true
  50740. });
  50741. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  50742. /**
  50743. * Sets a callback that will be triggered when the system is disposed.
  50744. */
  50745. set: function (callback) {
  50746. if (this._onDisposeObserver) {
  50747. this.onDisposeObservable.remove(this._onDisposeObserver);
  50748. }
  50749. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50750. },
  50751. enumerable: true,
  50752. configurable: true
  50753. });
  50754. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  50755. /**
  50756. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  50757. */
  50758. get: function () {
  50759. return this._isAnimationSheetEnabled;
  50760. },
  50761. enumerable: true,
  50762. configurable: true
  50763. });
  50764. Object.defineProperty(ParticleSystem.prototype, "particles", {
  50765. /**
  50766. * Gets the current list of active particles
  50767. */
  50768. get: function () {
  50769. return this._particles;
  50770. },
  50771. enumerable: true,
  50772. configurable: true
  50773. });
  50774. /**
  50775. * Returns the string "ParticleSystem"
  50776. * @returns a string containing the class name
  50777. */
  50778. ParticleSystem.prototype.getClassName = function () {
  50779. return "ParticleSystem";
  50780. };
  50781. ParticleSystem.prototype._createIndexBuffer = function () {
  50782. var indices = [];
  50783. var index = 0;
  50784. for (var count = 0; count < this._capacity; count++) {
  50785. indices.push(index);
  50786. indices.push(index + 1);
  50787. indices.push(index + 2);
  50788. indices.push(index);
  50789. indices.push(index + 2);
  50790. indices.push(index + 3);
  50791. index += 4;
  50792. }
  50793. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  50794. };
  50795. /**
  50796. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  50797. * Its lifetime will start back at 0.
  50798. * @param particle The particle to recycle
  50799. */
  50800. ParticleSystem.prototype.recycleParticle = function (particle) {
  50801. var lastParticle = this._particles.pop();
  50802. if (lastParticle !== particle) {
  50803. lastParticle.copyTo(particle);
  50804. this._stockParticles.push(lastParticle);
  50805. }
  50806. };
  50807. /**
  50808. * Gets the maximum number of particles active at the same time.
  50809. * @returns The max number of active particles.
  50810. */
  50811. ParticleSystem.prototype.getCapacity = function () {
  50812. return this._capacity;
  50813. };
  50814. /**
  50815. * Gets Wether there are still active particles in the system.
  50816. * @returns True if it is alive, otherwise false.
  50817. */
  50818. ParticleSystem.prototype.isAlive = function () {
  50819. return this._alive;
  50820. };
  50821. /**
  50822. * Gets Wether the system has been started.
  50823. * @returns True if it has been started, otherwise false.
  50824. */
  50825. ParticleSystem.prototype.isStarted = function () {
  50826. return this._started;
  50827. };
  50828. /**
  50829. * Starts the particle system and begins to emit.
  50830. */
  50831. ParticleSystem.prototype.start = function () {
  50832. this._started = true;
  50833. this._stopped = false;
  50834. this._actualFrame = 0;
  50835. };
  50836. /**
  50837. * Stops the particle system.
  50838. */
  50839. ParticleSystem.prototype.stop = function () {
  50840. this._stopped = true;
  50841. };
  50842. /**
  50843. * Remove all active particles
  50844. */
  50845. ParticleSystem.prototype.reset = function () {
  50846. this._stockParticles = [];
  50847. this._particles = [];
  50848. };
  50849. /**
  50850. * @ignore (for internal use only)
  50851. */
  50852. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  50853. var offset = index * this._vertexBufferSize;
  50854. this._vertexData[offset] = particle.position.x;
  50855. this._vertexData[offset + 1] = particle.position.y;
  50856. this._vertexData[offset + 2] = particle.position.z;
  50857. this._vertexData[offset + 3] = particle.color.r;
  50858. this._vertexData[offset + 4] = particle.color.g;
  50859. this._vertexData[offset + 5] = particle.color.b;
  50860. this._vertexData[offset + 6] = particle.color.a;
  50861. this._vertexData[offset + 7] = particle.angle;
  50862. this._vertexData[offset + 8] = particle.size;
  50863. this._vertexData[offset + 9] = offsetX;
  50864. this._vertexData[offset + 10] = offsetY;
  50865. };
  50866. /**
  50867. * @ignore (for internal use only)
  50868. */
  50869. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  50870. if (offsetX === 0)
  50871. offsetX = this._epsilon;
  50872. else if (offsetX === 1)
  50873. offsetX = 1 - this._epsilon;
  50874. if (offsetY === 0)
  50875. offsetY = this._epsilon;
  50876. else if (offsetY === 1)
  50877. offsetY = 1 - this._epsilon;
  50878. var offset = index * this._vertexBufferSize;
  50879. this._vertexData[offset] = particle.position.x;
  50880. this._vertexData[offset + 1] = particle.position.y;
  50881. this._vertexData[offset + 2] = particle.position.z;
  50882. this._vertexData[offset + 3] = particle.color.r;
  50883. this._vertexData[offset + 4] = particle.color.g;
  50884. this._vertexData[offset + 5] = particle.color.b;
  50885. this._vertexData[offset + 6] = particle.color.a;
  50886. this._vertexData[offset + 7] = particle.angle;
  50887. this._vertexData[offset + 8] = particle.size;
  50888. this._vertexData[offset + 9] = offsetX;
  50889. this._vertexData[offset + 10] = offsetY;
  50890. this._vertexData[offset + 11] = particle.cellIndex;
  50891. };
  50892. ParticleSystem.prototype._update = function (newParticles) {
  50893. // Update current
  50894. this._alive = this._particles.length > 0;
  50895. this.updateFunction(this._particles);
  50896. // Add new ones
  50897. var worldMatrix;
  50898. if (this.emitter.position) {
  50899. var emitterMesh = this.emitter;
  50900. worldMatrix = emitterMesh.getWorldMatrix();
  50901. }
  50902. else {
  50903. var emitterPosition = this.emitter;
  50904. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  50905. }
  50906. var particle;
  50907. for (var index = 0; index < newParticles; index++) {
  50908. if (this._particles.length === this._capacity) {
  50909. break;
  50910. }
  50911. if (this._stockParticles.length !== 0) {
  50912. particle = this._stockParticles.pop();
  50913. particle.age = 0;
  50914. particle.cellIndex = this.startSpriteCellID;
  50915. }
  50916. else {
  50917. particle = new BABYLON.Particle(this);
  50918. }
  50919. this._particles.push(particle);
  50920. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  50921. if (this.startPositionFunction) {
  50922. this.startPositionFunction(worldMatrix, particle.position, particle);
  50923. }
  50924. else {
  50925. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  50926. }
  50927. if (this.startDirectionFunction) {
  50928. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50929. }
  50930. else {
  50931. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50932. }
  50933. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  50934. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  50935. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  50936. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  50937. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  50938. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  50939. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  50940. }
  50941. };
  50942. ParticleSystem.prototype._getEffect = function () {
  50943. if (this._customEffect) {
  50944. return this._customEffect;
  50945. }
  50946. ;
  50947. var defines = [];
  50948. if (this._scene.clipPlane) {
  50949. defines.push("#define CLIPPLANE");
  50950. }
  50951. if (this._isAnimationSheetEnabled) {
  50952. defines.push("#define ANIMATESHEET");
  50953. }
  50954. // Effect
  50955. var join = defines.join("\n");
  50956. if (this._cachedDefines !== join) {
  50957. this._cachedDefines = join;
  50958. var attributesNamesOrOptions;
  50959. var effectCreationOption;
  50960. if (this._isAnimationSheetEnabled) {
  50961. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  50962. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  50963. }
  50964. else {
  50965. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  50966. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  50967. }
  50968. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  50969. }
  50970. return this._effect;
  50971. };
  50972. /**
  50973. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  50974. */
  50975. ParticleSystem.prototype.animate = function () {
  50976. if (!this._started)
  50977. return;
  50978. var effect = this._getEffect();
  50979. // Check
  50980. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  50981. return;
  50982. if (this._currentRenderId === this._scene.getRenderId()) {
  50983. return;
  50984. }
  50985. this._currentRenderId = this._scene.getRenderId();
  50986. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  50987. // determine the number of particles we need to create
  50988. var newParticles;
  50989. if (this.manualEmitCount > -1) {
  50990. newParticles = this.manualEmitCount;
  50991. this._newPartsExcess = 0;
  50992. this.manualEmitCount = 0;
  50993. }
  50994. else {
  50995. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  50996. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  50997. }
  50998. if (this._newPartsExcess > 1.0) {
  50999. newParticles += this._newPartsExcess >> 0;
  51000. this._newPartsExcess -= this._newPartsExcess >> 0;
  51001. }
  51002. this._alive = false;
  51003. if (!this._stopped) {
  51004. this._actualFrame += this._scaledUpdateSpeed;
  51005. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  51006. this.stop();
  51007. }
  51008. else {
  51009. newParticles = 0;
  51010. }
  51011. this._update(newParticles);
  51012. // Stopped?
  51013. if (this._stopped) {
  51014. if (!this._alive) {
  51015. this._started = false;
  51016. if (this.onAnimationEnd) {
  51017. this.onAnimationEnd();
  51018. }
  51019. if (this.disposeOnStop) {
  51020. this._scene._toBeDisposed.push(this);
  51021. }
  51022. }
  51023. }
  51024. // Animation sheet
  51025. if (this._isAnimationSheetEnabled) {
  51026. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  51027. }
  51028. else {
  51029. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  51030. }
  51031. // Update VBO
  51032. var offset = 0;
  51033. for (var index = 0; index < this._particles.length; index++) {
  51034. var particle = this._particles[index];
  51035. this._appendParticleVertexes(offset, particle);
  51036. offset += 4;
  51037. }
  51038. if (this._vertexBuffer) {
  51039. this._vertexBuffer.update(this._vertexData);
  51040. }
  51041. };
  51042. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  51043. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  51044. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  51045. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  51046. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  51047. };
  51048. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  51049. this._appendParticleVertex(offset++, particle, 0, 0);
  51050. this._appendParticleVertex(offset++, particle, 1, 0);
  51051. this._appendParticleVertex(offset++, particle, 1, 1);
  51052. this._appendParticleVertex(offset++, particle, 0, 1);
  51053. };
  51054. /**
  51055. * Rebuilds the particle system.
  51056. */
  51057. ParticleSystem.prototype.rebuild = function () {
  51058. this._createIndexBuffer();
  51059. if (this._vertexBuffer) {
  51060. this._vertexBuffer._rebuild();
  51061. }
  51062. };
  51063. /**
  51064. * Renders the particle system in its current state.
  51065. * @returns the current number of particles
  51066. */
  51067. ParticleSystem.prototype.render = function () {
  51068. var effect = this._getEffect();
  51069. // Check
  51070. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length) {
  51071. return 0;
  51072. }
  51073. var engine = this._scene.getEngine();
  51074. // Render
  51075. engine.enableEffect(effect);
  51076. engine.setState(false);
  51077. var viewMatrix = this._scene.getViewMatrix();
  51078. effect.setTexture("diffuseSampler", this.particleTexture);
  51079. effect.setMatrix("view", viewMatrix);
  51080. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  51081. if (this._isAnimationSheetEnabled) {
  51082. var baseSize = this.particleTexture.getBaseSize();
  51083. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  51084. }
  51085. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  51086. if (this._scene.clipPlane) {
  51087. var clipPlane = this._scene.clipPlane;
  51088. var invView = viewMatrix.clone();
  51089. invView.invert();
  51090. effect.setMatrix("invView", invView);
  51091. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  51092. }
  51093. // VBOs
  51094. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  51095. // Draw order
  51096. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  51097. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  51098. }
  51099. else {
  51100. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  51101. }
  51102. if (this.forceDepthWrite) {
  51103. engine.setDepthWrite(true);
  51104. }
  51105. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  51106. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  51107. return this._particles.length;
  51108. };
  51109. /**
  51110. * Disposes the particle system and free the associated resources
  51111. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  51112. */
  51113. ParticleSystem.prototype.dispose = function (disposeTexture) {
  51114. if (disposeTexture === void 0) { disposeTexture = true; }
  51115. if (this._vertexBuffer) {
  51116. this._vertexBuffer.dispose();
  51117. this._vertexBuffer = null;
  51118. }
  51119. if (this._indexBuffer) {
  51120. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  51121. this._indexBuffer = null;
  51122. }
  51123. if (disposeTexture && this.particleTexture) {
  51124. this.particleTexture.dispose();
  51125. this.particleTexture = null;
  51126. }
  51127. // Remove from scene
  51128. var index = this._scene.particleSystems.indexOf(this);
  51129. if (index > -1) {
  51130. this._scene.particleSystems.splice(index, 1);
  51131. }
  51132. // Callback
  51133. this.onDisposeObservable.notifyObservers(this);
  51134. this.onDisposeObservable.clear();
  51135. };
  51136. /**
  51137. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  51138. * @param radius The radius of the sphere to emit from
  51139. * @returns the emitter
  51140. */
  51141. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  51142. if (radius === void 0) { radius = 1; }
  51143. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  51144. this.particleEmitterType = particleEmitter;
  51145. return particleEmitter;
  51146. };
  51147. /**
  51148. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  51149. * @param radius The radius of the sphere to emit from
  51150. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  51151. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  51152. * @returns the emitter
  51153. */
  51154. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  51155. if (radius === void 0) { radius = 1; }
  51156. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  51157. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  51158. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  51159. this.particleEmitterType = particleEmitter;
  51160. return particleEmitter;
  51161. };
  51162. /**
  51163. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  51164. * @param radius The radius of the cone to emit from
  51165. * @param angle The base angle of the cone
  51166. * @returns the emitter
  51167. */
  51168. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  51169. if (radius === void 0) { radius = 1; }
  51170. if (angle === void 0) { angle = Math.PI / 4; }
  51171. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  51172. this.particleEmitterType = particleEmitter;
  51173. return particleEmitter;
  51174. };
  51175. // 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.
  51176. /**
  51177. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  51178. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  51179. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  51180. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51181. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51182. * @returns the emitter
  51183. */
  51184. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  51185. var particleEmitter = new BABYLON.BoxParticleEmitter();
  51186. this.direction1 = direction1;
  51187. this.direction2 = direction2;
  51188. this.minEmitBox = minEmitBox;
  51189. this.maxEmitBox = maxEmitBox;
  51190. this.particleEmitterType = particleEmitter;
  51191. return particleEmitter;
  51192. };
  51193. /**
  51194. * Clones the particle system.
  51195. * @param name The name of the cloned object
  51196. * @param newEmitter The new emitter to use
  51197. * @returns the cloned particle system
  51198. */
  51199. ParticleSystem.prototype.clone = function (name, newEmitter) {
  51200. var custom = null;
  51201. var program = null;
  51202. if (this.customShader != null) {
  51203. program = this.customShader;
  51204. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51205. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51206. }
  51207. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  51208. result.customShader = program;
  51209. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  51210. if (newEmitter === undefined) {
  51211. newEmitter = this.emitter;
  51212. }
  51213. result.emitter = newEmitter;
  51214. if (this.particleTexture) {
  51215. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  51216. }
  51217. if (!this.preventAutoStart) {
  51218. result.start();
  51219. }
  51220. return result;
  51221. };
  51222. /**
  51223. * Serializes the particle system to a JSON object.
  51224. * @returns the JSON object
  51225. */
  51226. ParticleSystem.prototype.serialize = function () {
  51227. var serializationObject = {};
  51228. serializationObject.name = this.name;
  51229. serializationObject.id = this.id;
  51230. // Emitter
  51231. if (this.emitter.position) {
  51232. var emitterMesh = this.emitter;
  51233. serializationObject.emitterId = emitterMesh.id;
  51234. }
  51235. else {
  51236. var emitterPosition = this.emitter;
  51237. serializationObject.emitter = emitterPosition.asArray();
  51238. }
  51239. serializationObject.capacity = this.getCapacity();
  51240. if (this.particleTexture) {
  51241. serializationObject.textureName = this.particleTexture.name;
  51242. }
  51243. // Animations
  51244. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  51245. // Particle system
  51246. serializationObject.minAngularSpeed = this.minAngularSpeed;
  51247. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  51248. serializationObject.minSize = this.minSize;
  51249. serializationObject.maxSize = this.maxSize;
  51250. serializationObject.minEmitPower = this.minEmitPower;
  51251. serializationObject.maxEmitPower = this.maxEmitPower;
  51252. serializationObject.minLifeTime = this.minLifeTime;
  51253. serializationObject.maxLifeTime = this.maxLifeTime;
  51254. serializationObject.emitRate = this.emitRate;
  51255. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51256. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51257. serializationObject.gravity = this.gravity.asArray();
  51258. serializationObject.direction1 = this.direction1.asArray();
  51259. serializationObject.direction2 = this.direction2.asArray();
  51260. serializationObject.color1 = this.color1.asArray();
  51261. serializationObject.color2 = this.color2.asArray();
  51262. serializationObject.colorDead = this.colorDead.asArray();
  51263. serializationObject.updateSpeed = this.updateSpeed;
  51264. serializationObject.targetStopDuration = this.targetStopDuration;
  51265. serializationObject.textureMask = this.textureMask.asArray();
  51266. serializationObject.blendMode = this.blendMode;
  51267. serializationObject.customShader = this.customShader;
  51268. serializationObject.preventAutoStart = this.preventAutoStart;
  51269. serializationObject.startSpriteCellID = this.startSpriteCellID;
  51270. serializationObject.endSpriteCellID = this.endSpriteCellID;
  51271. serializationObject.spriteCellLoop = this.spriteCellLoop;
  51272. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  51273. serializationObject.spriteCellWidth = this.spriteCellWidth;
  51274. serializationObject.spriteCellHeight = this.spriteCellHeight;
  51275. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  51276. // Emitter
  51277. if (this.particleEmitterType) {
  51278. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  51279. }
  51280. return serializationObject;
  51281. };
  51282. /**
  51283. * Parses a JSON object to create a particle system.
  51284. * @param parsedParticleSystem The JSON object to parse
  51285. * @param scene The scene to create the particle system in
  51286. * @param rootUrl The root url to use to load external dependencies like texture
  51287. * @returns the Parsed particle system
  51288. */
  51289. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  51290. var name = parsedParticleSystem.name;
  51291. var custom = null;
  51292. var program = null;
  51293. if (parsedParticleSystem.customShader) {
  51294. program = parsedParticleSystem.customShader;
  51295. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51296. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51297. }
  51298. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  51299. particleSystem.customShader = program;
  51300. if (parsedParticleSystem.id) {
  51301. particleSystem.id = parsedParticleSystem.id;
  51302. }
  51303. // Auto start
  51304. if (parsedParticleSystem.preventAutoStart) {
  51305. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  51306. }
  51307. // Texture
  51308. if (parsedParticleSystem.textureName) {
  51309. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  51310. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  51311. }
  51312. // Emitter
  51313. if (parsedParticleSystem.emitterId) {
  51314. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  51315. }
  51316. else {
  51317. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  51318. }
  51319. // Animations
  51320. if (parsedParticleSystem.animations) {
  51321. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  51322. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  51323. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  51324. }
  51325. }
  51326. if (parsedParticleSystem.autoAnimate) {
  51327. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  51328. }
  51329. // Particle system
  51330. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  51331. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  51332. particleSystem.minSize = parsedParticleSystem.minSize;
  51333. particleSystem.maxSize = parsedParticleSystem.maxSize;
  51334. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  51335. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  51336. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  51337. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  51338. particleSystem.emitRate = parsedParticleSystem.emitRate;
  51339. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  51340. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  51341. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  51342. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  51343. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  51344. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  51345. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  51346. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  51347. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  51348. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  51349. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  51350. particleSystem.blendMode = parsedParticleSystem.blendMode;
  51351. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  51352. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  51353. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  51354. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  51355. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  51356. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  51357. if (!particleSystem.preventAutoStart) {
  51358. particleSystem.start();
  51359. }
  51360. return particleSystem;
  51361. };
  51362. /**
  51363. * Source color is added to the destination color without alpha affecting the result.
  51364. */
  51365. ParticleSystem.BLENDMODE_ONEONE = 0;
  51366. /**
  51367. * Blend current color and particle color using particle’s alpha.
  51368. */
  51369. ParticleSystem.BLENDMODE_STANDARD = 1;
  51370. return ParticleSystem;
  51371. }());
  51372. BABYLON.ParticleSystem = ParticleSystem;
  51373. })(BABYLON || (BABYLON = {}));
  51374. //# sourceMappingURL=babylon.particleSystem.js.map
  51375. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  51376. var BABYLON;
  51377. (function (BABYLON) {
  51378. /**
  51379. * Particle emitter emitting particles from the inside of a box.
  51380. * It emits the particles randomly between 2 given directions.
  51381. */
  51382. var BoxParticleEmitter = /** @class */ (function () {
  51383. /**
  51384. * Creates a new instance of @see BoxParticleEmitter
  51385. */
  51386. function BoxParticleEmitter() {
  51387. /**
  51388. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51389. */
  51390. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  51391. /**
  51392. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51393. */
  51394. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  51395. /**
  51396. * 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.
  51397. */
  51398. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  51399. /**
  51400. * 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.
  51401. */
  51402. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  51403. }
  51404. /**
  51405. * Called by the particle System when the direction is computed for the created particle.
  51406. * @param emitPower is the power of the particle (speed)
  51407. * @param worldMatrix is the world matrix of the particle system
  51408. * @param directionToUpdate is the direction vector to update with the result
  51409. * @param particle is the particle we are computed the direction for
  51410. */
  51411. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51412. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51413. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51414. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51415. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51416. };
  51417. /**
  51418. * Called by the particle System when the position is computed for the created particle.
  51419. * @param worldMatrix is the world matrix of the particle system
  51420. * @param positionToUpdate is the position vector to update with the result
  51421. * @param particle is the particle we are computed the position for
  51422. */
  51423. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51424. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  51425. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  51426. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  51427. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51428. };
  51429. /**
  51430. * Clones the current emitter and returns a copy of it
  51431. * @returns the new emitter
  51432. */
  51433. BoxParticleEmitter.prototype.clone = function () {
  51434. var newOne = new BoxParticleEmitter();
  51435. BABYLON.Tools.DeepCopy(this, newOne);
  51436. return newOne;
  51437. };
  51438. /**
  51439. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51440. * @param effect defines the update shader
  51441. */
  51442. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  51443. effect.setVector3("direction1", this.direction1);
  51444. effect.setVector3("direction2", this.direction2);
  51445. effect.setVector3("minEmitBox", this.minEmitBox);
  51446. effect.setVector3("maxEmitBox", this.maxEmitBox);
  51447. };
  51448. /**
  51449. * Returns a string to use to update the GPU particles update shader
  51450. * @returns a string containng the defines string
  51451. */
  51452. BoxParticleEmitter.prototype.getEffectDefines = function () {
  51453. return "#define BOXEMITTER";
  51454. };
  51455. /**
  51456. * Returns the string "BoxEmitter"
  51457. * @returns a string containing the class name
  51458. */
  51459. BoxParticleEmitter.prototype.getClassName = function () {
  51460. return "BoxEmitter";
  51461. };
  51462. /**
  51463. * Serializes the particle system to a JSON object.
  51464. * @returns the JSON object
  51465. */
  51466. BoxParticleEmitter.prototype.serialize = function () {
  51467. var serializationObject = {};
  51468. serializationObject.type = this.getClassName();
  51469. serializationObject.direction1 = this.direction1.asArray();
  51470. ;
  51471. serializationObject.direction2 = this.direction2.asArray();
  51472. ;
  51473. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51474. ;
  51475. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51476. ;
  51477. return serializationObject;
  51478. };
  51479. /**
  51480. * Parse properties from a JSON object
  51481. * @param serializationObject defines the JSON object
  51482. */
  51483. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  51484. this.direction1.copyFrom(serializationObject.direction1);
  51485. this.direction2.copyFrom(serializationObject.direction2);
  51486. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  51487. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  51488. };
  51489. return BoxParticleEmitter;
  51490. }());
  51491. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  51492. })(BABYLON || (BABYLON = {}));
  51493. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  51494. var BABYLON;
  51495. (function (BABYLON) {
  51496. /**
  51497. * Particle emitter emitting particles from the inside of a cone.
  51498. * It emits the particles alongside the cone volume from the base to the particle.
  51499. * The emission direction might be randomized.
  51500. */
  51501. var ConeParticleEmitter = /** @class */ (function () {
  51502. /**
  51503. * Creates a new instance of @see ConeParticleEmitter
  51504. * @param radius the radius of the emission cone (1 by default)
  51505. * @param angles the cone base angle (PI by default)
  51506. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51507. */
  51508. function ConeParticleEmitter(radius,
  51509. /**
  51510. * The radius of the emission cone.
  51511. */
  51512. angle,
  51513. /**
  51514. * The cone base angle.
  51515. */
  51516. directionRandomizer) {
  51517. if (radius === void 0) { radius = 1; }
  51518. if (angle === void 0) { angle = Math.PI; }
  51519. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51520. this.angle = angle;
  51521. this.directionRandomizer = directionRandomizer;
  51522. this.radius = radius;
  51523. }
  51524. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  51525. /**
  51526. * Gets the radius of the emission cone.
  51527. */
  51528. get: function () {
  51529. return this._radius;
  51530. },
  51531. /**
  51532. * Sets the radius of the emission cone.
  51533. */
  51534. set: function (value) {
  51535. this._radius = value;
  51536. if (this.angle !== 0) {
  51537. this._height = value / Math.tan(this.angle / 2);
  51538. }
  51539. else {
  51540. this._height = 1;
  51541. }
  51542. },
  51543. enumerable: true,
  51544. configurable: true
  51545. });
  51546. /**
  51547. * Called by the particle System when the direction is computed for the created particle.
  51548. * @param emitPower is the power of the particle (speed)
  51549. * @param worldMatrix is the world matrix of the particle system
  51550. * @param directionToUpdate is the direction vector to update with the result
  51551. * @param particle is the particle we are computed the direction for
  51552. */
  51553. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51554. if (this.angle === 0) {
  51555. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  51556. }
  51557. else {
  51558. // measure the direction Vector from the emitter to the particle.
  51559. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51560. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51561. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51562. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51563. direction.x += randX;
  51564. direction.y += randY;
  51565. direction.z += randZ;
  51566. direction.normalize();
  51567. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51568. }
  51569. };
  51570. /**
  51571. * Called by the particle System when the position is computed for the created particle.
  51572. * @param worldMatrix is the world matrix of the particle system
  51573. * @param positionToUpdate is the position vector to update with the result
  51574. * @param particle is the particle we are computed the position for
  51575. */
  51576. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51577. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  51578. var h = BABYLON.Scalar.RandomRange(0, 1);
  51579. // Better distribution in a cone at normal angles.
  51580. h = 1 - h * h;
  51581. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  51582. radius = radius * h / this._height;
  51583. var randX = radius * Math.sin(s);
  51584. var randZ = radius * Math.cos(s);
  51585. var randY = h * this._height;
  51586. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51587. };
  51588. /**
  51589. * Clones the current emitter and returns a copy of it
  51590. * @returns the new emitter
  51591. */
  51592. ConeParticleEmitter.prototype.clone = function () {
  51593. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  51594. BABYLON.Tools.DeepCopy(this, newOne);
  51595. return newOne;
  51596. };
  51597. /**
  51598. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51599. * @param effect defines the update shader
  51600. */
  51601. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  51602. effect.setFloat("radius", this.radius);
  51603. effect.setFloat("angle", this.angle);
  51604. effect.setFloat("height", this._height);
  51605. effect.setFloat("directionRandomizer", this.directionRandomizer);
  51606. };
  51607. /**
  51608. * Returns a string to use to update the GPU particles update shader
  51609. * @returns a string containng the defines string
  51610. */
  51611. ConeParticleEmitter.prototype.getEffectDefines = function () {
  51612. return "#define CONEEMITTER";
  51613. };
  51614. /**
  51615. * Returns the string "BoxEmitter"
  51616. * @returns a string containing the class name
  51617. */
  51618. ConeParticleEmitter.prototype.getClassName = function () {
  51619. return "ConeEmitter";
  51620. };
  51621. /**
  51622. * Serializes the particle system to a JSON object.
  51623. * @returns the JSON object
  51624. */
  51625. ConeParticleEmitter.prototype.serialize = function () {
  51626. var serializationObject = {};
  51627. serializationObject.type = this.getClassName();
  51628. serializationObject.radius = this.radius;
  51629. serializationObject.angle = this.angle;
  51630. serializationObject.directionRandomizer = this.directionRandomizer;
  51631. return serializationObject;
  51632. };
  51633. /**
  51634. * Parse properties from a JSON object
  51635. * @param serializationObject defines the JSON object
  51636. */
  51637. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  51638. this.radius = serializationObject.radius;
  51639. this.angle = serializationObject.angle;
  51640. this.directionRandomizer = serializationObject.directionRandomizer;
  51641. };
  51642. return ConeParticleEmitter;
  51643. }());
  51644. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  51645. })(BABYLON || (BABYLON = {}));
  51646. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  51647. var BABYLON;
  51648. (function (BABYLON) {
  51649. /**
  51650. * Particle emitter emitting particles from the inside of a sphere.
  51651. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  51652. */
  51653. var SphereParticleEmitter = /** @class */ (function () {
  51654. /**
  51655. * Creates a new instance of @see SphereParticleEmitter
  51656. * @param radius the radius of the emission sphere (1 by default)
  51657. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51658. */
  51659. function SphereParticleEmitter(
  51660. /**
  51661. * The radius of the emission sphere.
  51662. */
  51663. radius,
  51664. /**
  51665. * How much to randomize the particle direction [0-1].
  51666. */
  51667. directionRandomizer) {
  51668. if (radius === void 0) { radius = 1; }
  51669. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51670. this.radius = radius;
  51671. this.directionRandomizer = directionRandomizer;
  51672. }
  51673. /**
  51674. * Called by the particle System when the direction is computed for the created particle.
  51675. * @param emitPower is the power of the particle (speed)
  51676. * @param worldMatrix is the world matrix of the particle system
  51677. * @param directionToUpdate is the direction vector to update with the result
  51678. * @param particle is the particle we are computed the direction for
  51679. */
  51680. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51681. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51682. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51683. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51684. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51685. direction.x += randX;
  51686. direction.y += randY;
  51687. direction.z += randZ;
  51688. direction.normalize();
  51689. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51690. };
  51691. /**
  51692. * Called by the particle System when the position is computed for the created particle.
  51693. * @param worldMatrix is the world matrix of the particle system
  51694. * @param positionToUpdate is the position vector to update with the result
  51695. * @param particle is the particle we are computed the position for
  51696. */
  51697. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51698. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  51699. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  51700. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  51701. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  51702. var randY = randRadius * Math.cos(theta);
  51703. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  51704. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51705. };
  51706. /**
  51707. * Clones the current emitter and returns a copy of it
  51708. * @returns the new emitter
  51709. */
  51710. SphereParticleEmitter.prototype.clone = function () {
  51711. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  51712. BABYLON.Tools.DeepCopy(this, newOne);
  51713. return newOne;
  51714. };
  51715. /**
  51716. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51717. * @param effect defines the update shader
  51718. */
  51719. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  51720. effect.setFloat("radius", this.radius);
  51721. effect.setFloat("directionRandomizer", this.directionRandomizer);
  51722. };
  51723. /**
  51724. * Returns a string to use to update the GPU particles update shader
  51725. * @returns a string containng the defines string
  51726. */
  51727. SphereParticleEmitter.prototype.getEffectDefines = function () {
  51728. return "#define SPHEREEMITTER";
  51729. };
  51730. /**
  51731. * Returns the string "SphereParticleEmitter"
  51732. * @returns a string containing the class name
  51733. */
  51734. SphereParticleEmitter.prototype.getClassName = function () {
  51735. return "SphereParticleEmitter";
  51736. };
  51737. /**
  51738. * Serializes the particle system to a JSON object.
  51739. * @returns the JSON object
  51740. */
  51741. SphereParticleEmitter.prototype.serialize = function () {
  51742. var serializationObject = {};
  51743. serializationObject.type = this.getClassName();
  51744. serializationObject.radius = this.radius;
  51745. serializationObject.directionRandomizer = this.directionRandomizer;
  51746. return serializationObject;
  51747. };
  51748. /**
  51749. * Parse properties from a JSON object
  51750. * @param serializationObject defines the JSON object
  51751. */
  51752. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  51753. this.radius = serializationObject.radius;
  51754. this.directionRandomizer = serializationObject.directionRandomizer;
  51755. };
  51756. return SphereParticleEmitter;
  51757. }());
  51758. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  51759. /**
  51760. * Particle emitter emitting particles from the inside of a sphere.
  51761. * It emits the particles randomly between two vectors.
  51762. */
  51763. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  51764. __extends(SphereDirectedParticleEmitter, _super);
  51765. /**
  51766. * Creates a new instance of @see SphereDirectedParticleEmitter
  51767. * @param radius the radius of the emission sphere (1 by default)
  51768. * @param direction1 the min limit of the emission direction (up vector by default)
  51769. * @param direction2 the max limit of the emission direction (up vector by default)
  51770. */
  51771. function SphereDirectedParticleEmitter(radius,
  51772. /**
  51773. * The min limit of the emission direction.
  51774. */
  51775. direction1,
  51776. /**
  51777. * The max limit of the emission direction.
  51778. */
  51779. direction2) {
  51780. if (radius === void 0) { radius = 1; }
  51781. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  51782. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  51783. var _this = _super.call(this, radius) || this;
  51784. _this.direction1 = direction1;
  51785. _this.direction2 = direction2;
  51786. return _this;
  51787. }
  51788. /**
  51789. * Called by the particle System when the direction is computed for the created particle.
  51790. * @param emitPower is the power of the particle (speed)
  51791. * @param worldMatrix is the world matrix of the particle system
  51792. * @param directionToUpdate is the direction vector to update with the result
  51793. * @param particle is the particle we are computed the direction for
  51794. */
  51795. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51796. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51797. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51798. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51799. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51800. };
  51801. /**
  51802. * Clones the current emitter and returns a copy of it
  51803. * @returns the new emitter
  51804. */
  51805. SphereDirectedParticleEmitter.prototype.clone = function () {
  51806. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  51807. BABYLON.Tools.DeepCopy(this, newOne);
  51808. return newOne;
  51809. };
  51810. /**
  51811. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51812. * @param effect defines the update shader
  51813. */
  51814. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  51815. effect.setFloat("radius", this.radius);
  51816. effect.setVector3("direction1", this.direction1);
  51817. effect.setVector3("direction2", this.direction2);
  51818. };
  51819. /**
  51820. * Returns a string to use to update the GPU particles update shader
  51821. * @returns a string containng the defines string
  51822. */
  51823. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  51824. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  51825. };
  51826. /**
  51827. * Returns the string "SphereDirectedParticleEmitter"
  51828. * @returns a string containing the class name
  51829. */
  51830. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  51831. return "SphereDirectedParticleEmitter";
  51832. };
  51833. /**
  51834. * Serializes the particle system to a JSON object.
  51835. * @returns the JSON object
  51836. */
  51837. SphereDirectedParticleEmitter.prototype.serialize = function () {
  51838. var serializationObject = _super.prototype.serialize.call(this);
  51839. ;
  51840. serializationObject.direction1 = this.direction1.asArray();
  51841. ;
  51842. serializationObject.direction2 = this.direction2.asArray();
  51843. ;
  51844. return serializationObject;
  51845. };
  51846. /**
  51847. * Parse properties from a JSON object
  51848. * @param serializationObject defines the JSON object
  51849. */
  51850. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  51851. _super.prototype.parse.call(this, serializationObject);
  51852. this.direction1.copyFrom(serializationObject.direction1);
  51853. this.direction2.copyFrom(serializationObject.direction2);
  51854. };
  51855. return SphereDirectedParticleEmitter;
  51856. }(SphereParticleEmitter));
  51857. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  51858. })(BABYLON || (BABYLON = {}));
  51859. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  51860. var __assign = (this && this.__assign) || Object.assign || function(t) {
  51861. for (var s, i = 1, n = arguments.length; i < n; i++) {
  51862. s = arguments[i];
  51863. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  51864. t[p] = s[p];
  51865. }
  51866. return t;
  51867. };
  51868. var BABYLON;
  51869. (function (BABYLON) {
  51870. /**
  51871. * This represents a GPU particle system in Babylon
  51872. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  51873. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  51874. */
  51875. var GPUParticleSystem = /** @class */ (function () {
  51876. /**
  51877. * Instantiates a GPU particle system.
  51878. * 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.
  51879. * @param name The name of the particle system
  51880. * @param capacity The max number of particles alive at the same time
  51881. * @param scene The scene the particle system belongs to
  51882. */
  51883. function GPUParticleSystem(name, options, scene) {
  51884. /**
  51885. * The emitter represents the Mesh or position we are attaching the particle system to.
  51886. */
  51887. this.emitter = null;
  51888. /**
  51889. * The rendering group used by the Particle system to chose when to render.
  51890. */
  51891. this.renderingGroupId = 0;
  51892. /**
  51893. * The layer mask we are rendering the particles through.
  51894. */
  51895. this.layerMask = 0x0FFFFFFF;
  51896. this._targetIndex = 0;
  51897. this._currentRenderId = -1;
  51898. this._started = false;
  51899. this._stopped = false;
  51900. this._timeDelta = 0;
  51901. this._attributesStrideSize = 14;
  51902. this._actualFrame = 0;
  51903. /**
  51904. * List of animations used by the particle system.
  51905. */
  51906. this.animations = [];
  51907. /**
  51908. * An event triggered when the system is disposed.
  51909. */
  51910. this.onDisposeObservable = new BABYLON.Observable();
  51911. /**
  51912. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  51913. */
  51914. this.updateSpeed = 0.01;
  51915. /**
  51916. * The amount of time the particle system is running (depends of the overall update speed).
  51917. */
  51918. this.targetStopDuration = 0;
  51919. /**
  51920. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  51921. */
  51922. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  51923. /**
  51924. * Minimum life time of emitting particles.
  51925. */
  51926. this.minLifeTime = 1;
  51927. /**
  51928. * Maximum life time of emitting particles.
  51929. */
  51930. this.maxLifeTime = 1;
  51931. /**
  51932. * Minimum Size of emitting particles.
  51933. */
  51934. this.minSize = 1;
  51935. /**
  51936. * Maximum Size of emitting particles.
  51937. */
  51938. this.maxSize = 1;
  51939. /**
  51940. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51941. */
  51942. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51943. /**
  51944. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51945. */
  51946. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51947. /**
  51948. * Color the particle will have at the end of its lifetime.
  51949. */
  51950. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  51951. /**
  51952. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  51953. */
  51954. this.emitRate = 100;
  51955. /**
  51956. * You can use gravity if you want to give an orientation to your particles.
  51957. */
  51958. this.gravity = BABYLON.Vector3.Zero();
  51959. /**
  51960. * Minimum power of emitting particles.
  51961. */
  51962. this.minEmitPower = 1;
  51963. /**
  51964. * Maximum power of emitting particles.
  51965. */
  51966. this.maxEmitPower = 1;
  51967. this.id = name;
  51968. this.name = name;
  51969. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51970. this._engine = this._scene.getEngine();
  51971. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  51972. this._capacity = fullOptions.capacity;
  51973. this._activeCount = fullOptions.capacity;
  51974. this._currentActiveCount = 0;
  51975. this._scene.particleSystems.push(this);
  51976. this._updateEffectOptions = {
  51977. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  51978. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  51979. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle"],
  51980. uniformBuffersNames: [],
  51981. samplers: ["randomSampler"],
  51982. defines: "",
  51983. fallbacks: null,
  51984. onCompiled: null,
  51985. onError: null,
  51986. indexParameters: null,
  51987. maxSimultaneousLights: 0,
  51988. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  51989. };
  51990. // Random data
  51991. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  51992. var d = [];
  51993. for (var i = 0; i < maxTextureSize; ++i) {
  51994. d.push(Math.random());
  51995. d.push(Math.random());
  51996. d.push(Math.random());
  51997. d.push(Math.random());
  51998. }
  51999. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA32F, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  52000. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52001. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52002. this._randomTextureSize = maxTextureSize;
  52003. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  52004. }
  52005. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  52006. /**
  52007. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  52008. */
  52009. get: function () {
  52010. if (!BABYLON.Engine.LastCreatedEngine) {
  52011. return false;
  52012. }
  52013. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  52014. },
  52015. enumerable: true,
  52016. configurable: true
  52017. });
  52018. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  52019. /**
  52020. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52021. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52022. */
  52023. get: function () {
  52024. if (this.particleEmitterType.direction1) {
  52025. return this.particleEmitterType.direction1;
  52026. }
  52027. return BABYLON.Vector3.Zero();
  52028. },
  52029. set: function (value) {
  52030. if (this.particleEmitterType.direction1) {
  52031. this.particleEmitterType.direction1 = value;
  52032. }
  52033. },
  52034. enumerable: true,
  52035. configurable: true
  52036. });
  52037. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  52038. /**
  52039. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52040. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52041. */
  52042. get: function () {
  52043. if (this.particleEmitterType.direction2) {
  52044. return this.particleEmitterType.direction2;
  52045. }
  52046. return BABYLON.Vector3.Zero();
  52047. },
  52048. set: function (value) {
  52049. if (this.particleEmitterType.direction2) {
  52050. this.particleEmitterType.direction2 = value;
  52051. }
  52052. },
  52053. enumerable: true,
  52054. configurable: true
  52055. });
  52056. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  52057. /**
  52058. * 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.
  52059. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52060. */
  52061. get: function () {
  52062. if (this.particleEmitterType.minEmitBox) {
  52063. return this.particleEmitterType.minEmitBox;
  52064. }
  52065. return BABYLON.Vector3.Zero();
  52066. },
  52067. set: function (value) {
  52068. if (this.particleEmitterType.minEmitBox) {
  52069. this.particleEmitterType.minEmitBox = value;
  52070. }
  52071. },
  52072. enumerable: true,
  52073. configurable: true
  52074. });
  52075. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  52076. /**
  52077. * 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.
  52078. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52079. */
  52080. get: function () {
  52081. if (this.particleEmitterType.maxEmitBox) {
  52082. return this.particleEmitterType.maxEmitBox;
  52083. }
  52084. return BABYLON.Vector3.Zero();
  52085. },
  52086. set: function (value) {
  52087. if (this.particleEmitterType.maxEmitBox) {
  52088. this.particleEmitterType.maxEmitBox = value;
  52089. }
  52090. },
  52091. enumerable: true,
  52092. configurable: true
  52093. });
  52094. /**
  52095. * Gets the maximum number of particles active at the same time.
  52096. * @returns The max number of active particles.
  52097. */
  52098. GPUParticleSystem.prototype.getCapacity = function () {
  52099. return this._capacity;
  52100. };
  52101. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  52102. /**
  52103. * Gets or set the number of active particles
  52104. */
  52105. get: function () {
  52106. return this._activeCount;
  52107. },
  52108. set: function (value) {
  52109. this._activeCount = Math.min(value, this._capacity);
  52110. },
  52111. enumerable: true,
  52112. configurable: true
  52113. });
  52114. /**
  52115. * Gets Wether the system has been started.
  52116. * @returns True if it has been started, otherwise false.
  52117. */
  52118. GPUParticleSystem.prototype.isStarted = function () {
  52119. return this._started;
  52120. };
  52121. /**
  52122. * Starts the particle system and begins to emit.
  52123. */
  52124. GPUParticleSystem.prototype.start = function () {
  52125. this._started = true;
  52126. this._stopped = false;
  52127. };
  52128. /**
  52129. * Stops the particle system.
  52130. */
  52131. GPUParticleSystem.prototype.stop = function () {
  52132. this._stopped = true;
  52133. };
  52134. /**
  52135. * Remove all active particles
  52136. */
  52137. GPUParticleSystem.prototype.reset = function () {
  52138. this._releaseBuffers();
  52139. this._releaseVAOs();
  52140. this._currentActiveCount = 0;
  52141. this._targetIndex = 0;
  52142. };
  52143. /**
  52144. * Returns the string "GPUParticleSystem"
  52145. * @returns a string containing the class name
  52146. */
  52147. GPUParticleSystem.prototype.getClassName = function () {
  52148. return "GPUParticleSystem";
  52149. };
  52150. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  52151. var updateVertexBuffers = {};
  52152. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  52153. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  52154. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  52155. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  52156. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  52157. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  52158. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  52159. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  52160. this._engine.bindArrayBuffer(null);
  52161. return vao;
  52162. };
  52163. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  52164. var renderVertexBuffers = {};
  52165. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  52166. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  52167. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  52168. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  52169. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  52170. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  52171. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  52172. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  52173. this._engine.bindArrayBuffer(null);
  52174. return vao;
  52175. };
  52176. GPUParticleSystem.prototype._initialize = function (force) {
  52177. if (force === void 0) { force = false; }
  52178. if (this._buffer0 && !force) {
  52179. return;
  52180. }
  52181. var engine = this._scene.getEngine();
  52182. var data = new Array();
  52183. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  52184. // position
  52185. data.push(0.0);
  52186. data.push(0.0);
  52187. data.push(0.0);
  52188. // Age and life
  52189. data.push(0.0); // create the particle as a dead one to create a new one at start
  52190. data.push(0.0);
  52191. // Seed
  52192. data.push(Math.random());
  52193. // Size
  52194. data.push(0.0);
  52195. // color
  52196. data.push(0.0);
  52197. data.push(0.0);
  52198. data.push(0.0);
  52199. data.push(0.0);
  52200. // direction
  52201. data.push(0.0);
  52202. data.push(0.0);
  52203. data.push(0.0);
  52204. }
  52205. // Sprite data
  52206. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  52207. -0.5, 0.5, 0, 1,
  52208. -0.5, -0.5, 0, 0,
  52209. 0.5, -0.5, 1, 0]);
  52210. // Buffers
  52211. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  52212. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  52213. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  52214. // Update VAO
  52215. this._updateVAO = [];
  52216. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  52217. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  52218. // Render VAO
  52219. this._renderVAO = [];
  52220. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  52221. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  52222. // Links
  52223. this._sourceBuffer = this._buffer0;
  52224. this._targetBuffer = this._buffer1;
  52225. };
  52226. /** @ignore */
  52227. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  52228. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  52229. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  52230. return;
  52231. }
  52232. this._updateEffectOptions.defines = defines;
  52233. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  52234. };
  52235. /** @ignore */
  52236. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  52237. var defines = "";
  52238. if (this._scene.clipPlane) {
  52239. defines = "\n#define CLIPPLANE";
  52240. }
  52241. if (this._renderEffect && this._renderEffect.defines === defines) {
  52242. return;
  52243. }
  52244. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  52245. };
  52246. /**
  52247. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  52248. */
  52249. GPUParticleSystem.prototype.animate = function () {
  52250. if (!this._stopped) {
  52251. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  52252. this._actualFrame += this._timeDelta;
  52253. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  52254. this.stop();
  52255. }
  52256. else {
  52257. this._timeDelta = 0;
  52258. }
  52259. };
  52260. /**
  52261. * Renders the particle system in its current state.
  52262. * @returns the current number of particles
  52263. */
  52264. GPUParticleSystem.prototype.render = function () {
  52265. if (!this._started) {
  52266. return 0;
  52267. }
  52268. this._recreateUpdateEffect();
  52269. this._recreateRenderEffect();
  52270. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady()) {
  52271. return 0;
  52272. }
  52273. if (this._currentRenderId === this._scene.getRenderId()) {
  52274. return 0;
  52275. }
  52276. this._currentRenderId = this._scene.getRenderId();
  52277. // Get everything ready to render
  52278. this._initialize();
  52279. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  52280. // Enable update effect
  52281. this._engine.enableEffect(this._updateEffect);
  52282. this._engine.setState(false);
  52283. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  52284. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  52285. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  52286. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  52287. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  52288. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  52289. this._updateEffect.setDirectColor4("color1", this.color1);
  52290. this._updateEffect.setDirectColor4("color2", this.color2);
  52291. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  52292. this._updateEffect.setVector3("gravity", this.gravity);
  52293. if (this.particleEmitterType) {
  52294. this.particleEmitterType.applyToShader(this._updateEffect);
  52295. }
  52296. var emitterWM;
  52297. if (this.emitter.position) {
  52298. var emitterMesh = this.emitter;
  52299. emitterWM = emitterMesh.getWorldMatrix();
  52300. }
  52301. else {
  52302. var emitterPosition = this.emitter;
  52303. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  52304. }
  52305. this._updateEffect.setMatrix("emitterWM", emitterWM);
  52306. // Bind source VAO
  52307. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  52308. // Update
  52309. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  52310. this._engine.setRasterizerState(false);
  52311. this._engine.beginTransformFeedback();
  52312. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  52313. this._engine.endTransformFeedback();
  52314. this._engine.setRasterizerState(true);
  52315. this._engine.bindTransformFeedbackBuffer(null);
  52316. // Enable render effect
  52317. this._engine.enableEffect(this._renderEffect);
  52318. var viewMatrix = this._scene.getViewMatrix();
  52319. this._renderEffect.setMatrix("view", viewMatrix);
  52320. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  52321. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  52322. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  52323. if (this._scene.clipPlane) {
  52324. var clipPlane = this._scene.clipPlane;
  52325. var invView = viewMatrix.clone();
  52326. invView.invert();
  52327. this._renderEffect.setMatrix("invView", invView);
  52328. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  52329. }
  52330. // Draw order
  52331. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  52332. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  52333. }
  52334. else {
  52335. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52336. }
  52337. // Bind source VAO
  52338. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  52339. // Render
  52340. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  52341. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52342. // Switch VAOs
  52343. this._targetIndex++;
  52344. if (this._targetIndex === 2) {
  52345. this._targetIndex = 0;
  52346. }
  52347. // Switch buffers
  52348. var tmpBuffer = this._sourceBuffer;
  52349. this._sourceBuffer = this._targetBuffer;
  52350. this._targetBuffer = tmpBuffer;
  52351. return this._currentActiveCount;
  52352. };
  52353. /**
  52354. * Rebuilds the particle system
  52355. */
  52356. GPUParticleSystem.prototype.rebuild = function () {
  52357. this._initialize(true);
  52358. };
  52359. GPUParticleSystem.prototype._releaseBuffers = function () {
  52360. if (this._buffer0) {
  52361. this._buffer0.dispose();
  52362. this._buffer0 = null;
  52363. }
  52364. if (this._buffer1) {
  52365. this._buffer1.dispose();
  52366. this._buffer1 = null;
  52367. }
  52368. if (this._spriteBuffer) {
  52369. this._spriteBuffer.dispose();
  52370. this._spriteBuffer = null;
  52371. }
  52372. };
  52373. GPUParticleSystem.prototype._releaseVAOs = function () {
  52374. for (var index = 0; index < this._updateVAO.length; index++) {
  52375. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  52376. }
  52377. this._updateVAO = [];
  52378. for (var index = 0; index < this._renderVAO.length; index++) {
  52379. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  52380. }
  52381. this._renderVAO = [];
  52382. };
  52383. /**
  52384. * Disposes the particle system and free the associated resources
  52385. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  52386. */
  52387. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  52388. if (disposeTexture === void 0) { disposeTexture = true; }
  52389. var index = this._scene.particleSystems.indexOf(this);
  52390. if (index > -1) {
  52391. this._scene.particleSystems.splice(index, 1);
  52392. }
  52393. this._releaseBuffers();
  52394. this._releaseVAOs();
  52395. if (this._randomTexture) {
  52396. this._randomTexture.dispose();
  52397. this._randomTexture = null;
  52398. }
  52399. if (disposeTexture && this.particleTexture) {
  52400. this.particleTexture.dispose();
  52401. this.particleTexture = null;
  52402. }
  52403. // Callback
  52404. this.onDisposeObservable.notifyObservers(this);
  52405. this.onDisposeObservable.clear();
  52406. };
  52407. /**
  52408. * Clones the particle system.
  52409. * @param name The name of the cloned object
  52410. * @param newEmitter The new emitter to use
  52411. * @returns the cloned particle system
  52412. */
  52413. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  52414. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  52415. BABYLON.Tools.DeepCopy(this, result);
  52416. if (newEmitter === undefined) {
  52417. newEmitter = this.emitter;
  52418. }
  52419. result.emitter = newEmitter;
  52420. if (this.particleTexture) {
  52421. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  52422. }
  52423. return result;
  52424. };
  52425. /**
  52426. * Serializes the particle system to a JSON object.
  52427. * @returns the JSON object
  52428. */
  52429. GPUParticleSystem.prototype.serialize = function () {
  52430. var serializationObject = {};
  52431. serializationObject.name = this.name;
  52432. serializationObject.id = this.id;
  52433. // Emitter
  52434. if (this.emitter.position) {
  52435. var emitterMesh = this.emitter;
  52436. serializationObject.emitterId = emitterMesh.id;
  52437. }
  52438. else {
  52439. var emitterPosition = this.emitter;
  52440. serializationObject.emitter = emitterPosition.asArray();
  52441. }
  52442. serializationObject.capacity = this.getCapacity();
  52443. if (this.particleTexture) {
  52444. serializationObject.textureName = this.particleTexture.name;
  52445. }
  52446. // Animations
  52447. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  52448. // Particle system
  52449. serializationObject.activeParticleCount = this.activeParticleCount;
  52450. serializationObject.randomTextureSize = this._randomTextureSize;
  52451. serializationObject.minSize = this.minSize;
  52452. serializationObject.maxSize = this.maxSize;
  52453. serializationObject.minEmitPower = this.minEmitPower;
  52454. serializationObject.maxEmitPower = this.maxEmitPower;
  52455. serializationObject.minLifeTime = this.minLifeTime;
  52456. serializationObject.maxLifeTime = this.maxLifeTime;
  52457. serializationObject.emitRate = this.emitRate;
  52458. serializationObject.gravity = this.gravity.asArray();
  52459. serializationObject.color1 = this.color1.asArray();
  52460. serializationObject.color2 = this.color2.asArray();
  52461. serializationObject.colorDead = this.colorDead.asArray();
  52462. serializationObject.updateSpeed = this.updateSpeed;
  52463. serializationObject.targetStopDuration = this.targetStopDuration;
  52464. serializationObject.blendMode = this.blendMode;
  52465. // Emitter
  52466. if (this.particleEmitterType) {
  52467. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  52468. }
  52469. return serializationObject;
  52470. };
  52471. /**
  52472. * Parses a JSON object to create a GPU particle system.
  52473. * @param parsedParticleSystem The JSON object to parse
  52474. * @param scene The scene to create the particle system in
  52475. * @param rootUrl The root url to use to load external dependencies like texture
  52476. * @returns the parsed GPU particle system
  52477. */
  52478. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  52479. var name = parsedParticleSystem.name;
  52480. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  52481. if (parsedParticleSystem.id) {
  52482. particleSystem.id = parsedParticleSystem.id;
  52483. }
  52484. // Texture
  52485. if (parsedParticleSystem.textureName) {
  52486. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  52487. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  52488. }
  52489. // Emitter
  52490. if (parsedParticleSystem.emitterId) {
  52491. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  52492. }
  52493. else {
  52494. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  52495. }
  52496. // Animations
  52497. if (parsedParticleSystem.animations) {
  52498. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  52499. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  52500. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  52501. }
  52502. }
  52503. // Particle system
  52504. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  52505. particleSystem.minSize = parsedParticleSystem.minSize;
  52506. particleSystem.maxSize = parsedParticleSystem.maxSize;
  52507. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  52508. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  52509. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  52510. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  52511. particleSystem.emitRate = parsedParticleSystem.emitRate;
  52512. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  52513. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  52514. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  52515. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  52516. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  52517. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  52518. particleSystem.blendMode = parsedParticleSystem.blendMode;
  52519. // Emitter
  52520. if (parsedParticleSystem.particleEmitterType) {
  52521. var emitterType = void 0;
  52522. switch (parsedParticleSystem.particleEmitterType.type) {
  52523. case "SphereEmitter":
  52524. emitterType = new BABYLON.SphereParticleEmitter();
  52525. break;
  52526. case "SphereDirectedParticleEmitter":
  52527. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  52528. break;
  52529. case "ConeEmitter":
  52530. emitterType = new BABYLON.ConeParticleEmitter();
  52531. break;
  52532. case "BoxEmitter":
  52533. default:
  52534. emitterType = new BABYLON.BoxParticleEmitter();
  52535. break;
  52536. }
  52537. emitterType.parse(parsedParticleSystem.particleEmitterType);
  52538. particleSystem.particleEmitterType = emitterType;
  52539. }
  52540. return particleSystem;
  52541. };
  52542. return GPUParticleSystem;
  52543. }());
  52544. BABYLON.GPUParticleSystem = GPUParticleSystem;
  52545. })(BABYLON || (BABYLON = {}));
  52546. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  52547. var BABYLON;
  52548. (function (BABYLON) {
  52549. /**
  52550. * Represents one particle of a solid particle system.
  52551. * @see SolidParticleSystem
  52552. */
  52553. var SolidParticle = /** @class */ (function () {
  52554. /**
  52555. * Creates a Solid Particle object.
  52556. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  52557. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  52558. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  52559. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  52560. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  52561. * @param shapeId (integer) is the model shape identifier in the SPS.
  52562. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  52563. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  52564. */
  52565. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  52566. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  52567. /**
  52568. * particle global index
  52569. */
  52570. this.idx = 0;
  52571. /**
  52572. * The color of the particle
  52573. */
  52574. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52575. /**
  52576. * The world space position of the particle.
  52577. */
  52578. this.position = BABYLON.Vector3.Zero();
  52579. /**
  52580. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  52581. */
  52582. this.rotation = BABYLON.Vector3.Zero();
  52583. /**
  52584. * The scaling of the particle.
  52585. */
  52586. this.scaling = BABYLON.Vector3.One();
  52587. /**
  52588. * The uvs of the particle.
  52589. */
  52590. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  52591. /**
  52592. * The current speed of the particle.
  52593. */
  52594. this.velocity = BABYLON.Vector3.Zero();
  52595. /**
  52596. * The pivot point in the particle local space.
  52597. */
  52598. this.pivot = BABYLON.Vector3.Zero();
  52599. /**
  52600. * Must the particle be translated from its pivot point in its local space ?
  52601. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  52602. * Default : false
  52603. */
  52604. this.translateFromPivot = false;
  52605. /**
  52606. * Is the particle active or not ?
  52607. */
  52608. this.alive = true;
  52609. /**
  52610. * Is the particle visible or not ?
  52611. */
  52612. this.isVisible = true;
  52613. /**
  52614. * Index of this particle in the global "positions" array (Internal use)
  52615. */
  52616. this._pos = 0;
  52617. /**
  52618. * Index of this particle in the global "indices" array (Internal use)
  52619. */
  52620. this._ind = 0;
  52621. /**
  52622. * ModelShape id of this particle
  52623. */
  52624. this.shapeId = 0;
  52625. /**
  52626. * Index of the particle in its shape id (Internal use)
  52627. */
  52628. this.idxInShape = 0;
  52629. /**
  52630. * Still set as invisible in order to skip useless computations (Internal use)
  52631. */
  52632. this._stillInvisible = false;
  52633. /**
  52634. * Last computed particle rotation matrix
  52635. */
  52636. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  52637. /**
  52638. * Parent particle Id, if any.
  52639. * Default null.
  52640. */
  52641. this.parentId = null;
  52642. /**
  52643. * Internal global position in the SPS.
  52644. */
  52645. this._globalPosition = BABYLON.Vector3.Zero();
  52646. this.idx = particleIndex;
  52647. this._pos = positionIndex;
  52648. this._ind = indiceIndex;
  52649. this._model = model;
  52650. this.shapeId = shapeId;
  52651. this.idxInShape = idxInShape;
  52652. this._sps = sps;
  52653. if (modelBoundingInfo) {
  52654. this._modelBoundingInfo = modelBoundingInfo;
  52655. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  52656. }
  52657. }
  52658. Object.defineProperty(SolidParticle.prototype, "scale", {
  52659. /**
  52660. * Legacy support, changed scale to scaling
  52661. */
  52662. get: function () {
  52663. return this.scaling;
  52664. },
  52665. /**
  52666. * Legacy support, changed scale to scaling
  52667. */
  52668. set: function (scale) {
  52669. this.scaling = scale;
  52670. },
  52671. enumerable: true,
  52672. configurable: true
  52673. });
  52674. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  52675. /**
  52676. * Legacy support, changed quaternion to rotationQuaternion
  52677. */
  52678. get: function () {
  52679. return this.rotationQuaternion;
  52680. },
  52681. /**
  52682. * Legacy support, changed quaternion to rotationQuaternion
  52683. */
  52684. set: function (q) {
  52685. this.rotationQuaternion = q;
  52686. },
  52687. enumerable: true,
  52688. configurable: true
  52689. });
  52690. /**
  52691. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  52692. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  52693. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  52694. * @returns true if it intersects
  52695. */
  52696. SolidParticle.prototype.intersectsMesh = function (target) {
  52697. if (!this._boundingInfo || !target._boundingInfo) {
  52698. return false;
  52699. }
  52700. if (this._sps._bSphereOnly) {
  52701. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  52702. }
  52703. return this._boundingInfo.intersects(target._boundingInfo, false);
  52704. };
  52705. return SolidParticle;
  52706. }());
  52707. BABYLON.SolidParticle = SolidParticle;
  52708. /**
  52709. * Represents the shape of the model used by one particle of a solid particle system.
  52710. * SPS internal tool, don't use it manually.
  52711. * @see SolidParticleSystem
  52712. */
  52713. var ModelShape = /** @class */ (function () {
  52714. /**
  52715. * 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.
  52716. * SPS internal tool, don't use it manually.
  52717. * @ignore
  52718. */
  52719. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  52720. /**
  52721. * length of the shape in the model indices array (internal use)
  52722. */
  52723. this._indicesLength = 0;
  52724. this.shapeID = id;
  52725. this._shape = shape;
  52726. this._indicesLength = indicesLength;
  52727. this._shapeUV = shapeUV;
  52728. this._positionFunction = posFunction;
  52729. this._vertexFunction = vtxFunction;
  52730. }
  52731. return ModelShape;
  52732. }());
  52733. BABYLON.ModelShape = ModelShape;
  52734. /**
  52735. * Represents a Depth Sorted Particle in the solid particle system.
  52736. * @see SolidParticleSystem
  52737. */
  52738. var DepthSortedParticle = /** @class */ (function () {
  52739. function DepthSortedParticle() {
  52740. /**
  52741. * Index of the particle in the "indices" array
  52742. */
  52743. this.ind = 0;
  52744. /**
  52745. * Length of the particle shape in the "indices" array
  52746. */
  52747. this.indicesLength = 0;
  52748. /**
  52749. * Squared distance from the particle to the camera
  52750. */
  52751. this.sqDistance = 0.0;
  52752. }
  52753. return DepthSortedParticle;
  52754. }());
  52755. BABYLON.DepthSortedParticle = DepthSortedParticle;
  52756. })(BABYLON || (BABYLON = {}));
  52757. //# sourceMappingURL=babylon.solidParticle.js.map
  52758. var BABYLON;
  52759. (function (BABYLON) {
  52760. /**
  52761. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  52762. *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.
  52763. * The SPS is also a particle system. It provides some methods to manage the particles.
  52764. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  52765. *
  52766. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  52767. */
  52768. var SolidParticleSystem = /** @class */ (function () {
  52769. /**
  52770. * Creates a SPS (Solid Particle System) object.
  52771. * @param name (String) is the SPS name, this will be the underlying mesh name.
  52772. * @param scene (Scene) is the scene in which the SPS is added.
  52773. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  52774. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  52775. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  52776. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  52777. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  52778. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  52779. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  52780. */
  52781. function SolidParticleSystem(name, scene, options) {
  52782. /**
  52783. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  52784. * Example : var p = SPS.particles[i];
  52785. */
  52786. this.particles = new Array();
  52787. /**
  52788. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  52789. */
  52790. this.nbParticles = 0;
  52791. /**
  52792. * If the particles must ever face the camera (default false). Useful for planar particles.
  52793. */
  52794. this.billboard = false;
  52795. /**
  52796. * Recompute normals when adding a shape
  52797. */
  52798. this.recomputeNormals = true;
  52799. /**
  52800. * This a counter ofr your own usage. It's not set by any SPS functions.
  52801. */
  52802. this.counter = 0;
  52803. /**
  52804. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  52805. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  52806. */
  52807. this.vars = {};
  52808. /**
  52809. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  52810. */
  52811. this._bSphereOnly = false;
  52812. /**
  52813. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  52814. */
  52815. this._bSphereRadiusFactor = 1.0;
  52816. this._positions = new Array();
  52817. this._indices = new Array();
  52818. this._normals = new Array();
  52819. this._colors = new Array();
  52820. this._uvs = new Array();
  52821. this._index = 0; // indices index
  52822. this._updatable = true;
  52823. this._pickable = false;
  52824. this._isVisibilityBoxLocked = false;
  52825. this._alwaysVisible = false;
  52826. this._depthSort = false;
  52827. this._shapeCounter = 0;
  52828. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  52829. this._color = new BABYLON.Color4(0, 0, 0, 0);
  52830. this._computeParticleColor = true;
  52831. this._computeParticleTexture = true;
  52832. this._computeParticleRotation = true;
  52833. this._computeParticleVertex = false;
  52834. this._computeBoundingBox = false;
  52835. this._depthSortParticles = true;
  52836. this._cam_axisZ = BABYLON.Vector3.Zero();
  52837. this._cam_axisY = BABYLON.Vector3.Zero();
  52838. this._cam_axisX = BABYLON.Vector3.Zero();
  52839. this._axisZ = BABYLON.Axis.Z;
  52840. this._camDir = BABYLON.Vector3.Zero();
  52841. this._camInvertedPosition = BABYLON.Vector3.Zero();
  52842. this._rotMatrix = new BABYLON.Matrix();
  52843. this._invertMatrix = new BABYLON.Matrix();
  52844. this._rotated = BABYLON.Vector3.Zero();
  52845. this._quaternion = new BABYLON.Quaternion();
  52846. this._vertex = BABYLON.Vector3.Zero();
  52847. this._normal = BABYLON.Vector3.Zero();
  52848. this._yaw = 0.0;
  52849. this._pitch = 0.0;
  52850. this._roll = 0.0;
  52851. this._halfroll = 0.0;
  52852. this._halfpitch = 0.0;
  52853. this._halfyaw = 0.0;
  52854. this._sinRoll = 0.0;
  52855. this._cosRoll = 0.0;
  52856. this._sinPitch = 0.0;
  52857. this._cosPitch = 0.0;
  52858. this._sinYaw = 0.0;
  52859. this._cosYaw = 0.0;
  52860. this._mustUnrotateFixedNormals = false;
  52861. this._minimum = BABYLON.Vector3.Zero();
  52862. this._maximum = BABYLON.Vector3.Zero();
  52863. this._minBbox = BABYLON.Vector3.Zero();
  52864. this._maxBbox = BABYLON.Vector3.Zero();
  52865. this._particlesIntersect = false;
  52866. this._depthSortFunction = function (p1, p2) {
  52867. return (p2.sqDistance - p1.sqDistance);
  52868. };
  52869. this._needs32Bits = false;
  52870. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  52871. this._scaledPivot = BABYLON.Vector3.Zero();
  52872. this._particleHasParent = false;
  52873. this.name = name;
  52874. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52875. this._camera = scene.activeCamera;
  52876. this._pickable = options ? options.isPickable : false;
  52877. this._depthSort = options ? options.enableDepthSort : false;
  52878. this._particlesIntersect = options ? options.particleIntersection : false;
  52879. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  52880. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  52881. if (options && options.updatable) {
  52882. this._updatable = options.updatable;
  52883. }
  52884. else {
  52885. this._updatable = true;
  52886. }
  52887. if (this._pickable) {
  52888. this.pickedParticles = [];
  52889. }
  52890. if (this._depthSort) {
  52891. this.depthSortedParticles = [];
  52892. }
  52893. }
  52894. /**
  52895. * Builds the SPS underlying mesh. Returns a standard Mesh.
  52896. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  52897. * @returns the created mesh
  52898. */
  52899. SolidParticleSystem.prototype.buildMesh = function () {
  52900. if (this.nbParticles === 0) {
  52901. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  52902. this.addShape(triangle, 1);
  52903. triangle.dispose();
  52904. }
  52905. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  52906. this._positions32 = new Float32Array(this._positions);
  52907. this._uvs32 = new Float32Array(this._uvs);
  52908. this._colors32 = new Float32Array(this._colors);
  52909. if (this.recomputeNormals) {
  52910. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  52911. }
  52912. this._normals32 = new Float32Array(this._normals);
  52913. this._fixedNormal32 = new Float32Array(this._normals);
  52914. if (this._mustUnrotateFixedNormals) {
  52915. this._unrotateFixedNormals();
  52916. }
  52917. var vertexData = new BABYLON.VertexData();
  52918. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  52919. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  52920. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  52921. if (this._uvs32) {
  52922. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  52923. ;
  52924. }
  52925. if (this._colors32) {
  52926. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  52927. }
  52928. var mesh = new BABYLON.Mesh(this.name, this._scene);
  52929. vertexData.applyToMesh(mesh, this._updatable);
  52930. this.mesh = mesh;
  52931. this.mesh.isPickable = this._pickable;
  52932. // free memory
  52933. if (!this._depthSort) {
  52934. this._indices = null;
  52935. }
  52936. this._positions = null;
  52937. this._normals = null;
  52938. this._uvs = null;
  52939. this._colors = null;
  52940. if (!this._updatable) {
  52941. this.particles.length = 0;
  52942. }
  52943. return mesh;
  52944. };
  52945. /**
  52946. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  52947. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  52948. * Thus the particles generated from `digest()` have their property `position` set yet.
  52949. * @param mesh ( Mesh ) is the mesh to be digested
  52950. * @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
  52951. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  52952. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  52953. * @returns the current SPS
  52954. */
  52955. SolidParticleSystem.prototype.digest = function (mesh, options) {
  52956. var size = (options && options.facetNb) || 1;
  52957. var number = (options && options.number) || 0;
  52958. var delta = (options && options.delta) || 0;
  52959. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52960. var meshInd = mesh.getIndices();
  52961. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52962. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52963. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52964. var f = 0; // facet counter
  52965. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  52966. // compute size from number
  52967. if (number) {
  52968. number = (number > totalFacets) ? totalFacets : number;
  52969. size = Math.round(totalFacets / number);
  52970. delta = 0;
  52971. }
  52972. else {
  52973. size = (size > totalFacets) ? totalFacets : size;
  52974. }
  52975. var facetPos = []; // submesh positions
  52976. var facetInd = []; // submesh indices
  52977. var facetUV = []; // submesh UV
  52978. var facetCol = []; // submesh colors
  52979. var barycenter = BABYLON.Vector3.Zero();
  52980. var sizeO = size;
  52981. while (f < totalFacets) {
  52982. size = sizeO + Math.floor((1 + delta) * Math.random());
  52983. if (f > totalFacets - size) {
  52984. size = totalFacets - f;
  52985. }
  52986. // reset temp arrays
  52987. facetPos.length = 0;
  52988. facetInd.length = 0;
  52989. facetUV.length = 0;
  52990. facetCol.length = 0;
  52991. // iterate over "size" facets
  52992. var fi = 0;
  52993. for (var j = f * 3; j < (f + size) * 3; j++) {
  52994. facetInd.push(fi);
  52995. var i = meshInd[j];
  52996. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  52997. if (meshUV) {
  52998. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  52999. }
  53000. if (meshCol) {
  53001. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  53002. }
  53003. fi++;
  53004. }
  53005. // create a model shape for each single particle
  53006. var idx = this.nbParticles;
  53007. var shape = this._posToShape(facetPos);
  53008. var shapeUV = this._uvsToShapeUV(facetUV);
  53009. // compute the barycenter of the shape
  53010. var v;
  53011. for (v = 0; v < shape.length; v++) {
  53012. barycenter.addInPlace(shape[v]);
  53013. }
  53014. barycenter.scaleInPlace(1 / shape.length);
  53015. // shift the shape from its barycenter to the origin
  53016. for (v = 0; v < shape.length; v++) {
  53017. shape[v].subtractInPlace(barycenter);
  53018. }
  53019. var bInfo;
  53020. if (this._particlesIntersect) {
  53021. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  53022. }
  53023. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  53024. // add the particle in the SPS
  53025. var currentPos = this._positions.length;
  53026. var currentInd = this._indices.length;
  53027. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  53028. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  53029. // initialize the particle position
  53030. this.particles[this.nbParticles].position.addInPlace(barycenter);
  53031. this._index += shape.length;
  53032. idx++;
  53033. this.nbParticles++;
  53034. this._shapeCounter++;
  53035. f += size;
  53036. }
  53037. return this;
  53038. };
  53039. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  53040. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  53041. var index = 0;
  53042. var idx = 0;
  53043. for (var p = 0; p < this.particles.length; p++) {
  53044. this._particle = this.particles[p];
  53045. this._shape = this._particle._model._shape;
  53046. if (this._particle.rotationQuaternion) {
  53047. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53048. }
  53049. else {
  53050. this._yaw = this._particle.rotation.y;
  53051. this._pitch = this._particle.rotation.x;
  53052. this._roll = this._particle.rotation.z;
  53053. this._quaternionRotationYPR();
  53054. }
  53055. this._quaternionToRotationMatrix();
  53056. this._rotMatrix.invertToRef(this._invertMatrix);
  53057. for (var pt = 0; pt < this._shape.length; pt++) {
  53058. idx = index + pt * 3;
  53059. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  53060. this._fixedNormal32[idx] = this._normal.x;
  53061. this._fixedNormal32[idx + 1] = this._normal.y;
  53062. this._fixedNormal32[idx + 2] = this._normal.z;
  53063. }
  53064. index = idx + 3;
  53065. }
  53066. };
  53067. //reset copy
  53068. SolidParticleSystem.prototype._resetCopy = function () {
  53069. this._copy.position.x = 0;
  53070. this._copy.position.y = 0;
  53071. this._copy.position.z = 0;
  53072. this._copy.rotation.x = 0;
  53073. this._copy.rotation.y = 0;
  53074. this._copy.rotation.z = 0;
  53075. this._copy.rotationQuaternion = null;
  53076. this._copy.scaling.x = 1.0;
  53077. this._copy.scaling.y = 1.0;
  53078. this._copy.scaling.z = 1.0;
  53079. this._copy.uvs.x = 0;
  53080. this._copy.uvs.y = 0;
  53081. this._copy.uvs.z = 1.0;
  53082. this._copy.uvs.w = 1.0;
  53083. this._copy.color = null;
  53084. this._copy.translateFromPivot = false;
  53085. };
  53086. // _meshBuilder : inserts the shape model in the global SPS mesh
  53087. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  53088. var i;
  53089. var u = 0;
  53090. var c = 0;
  53091. var n = 0;
  53092. this._resetCopy();
  53093. if (options && options.positionFunction) {
  53094. options.positionFunction(this._copy, idx, idxInShape);
  53095. this._mustUnrotateFixedNormals = true;
  53096. }
  53097. if (this._copy.rotationQuaternion) {
  53098. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  53099. }
  53100. else {
  53101. this._yaw = this._copy.rotation.y;
  53102. this._pitch = this._copy.rotation.x;
  53103. this._roll = this._copy.rotation.z;
  53104. this._quaternionRotationYPR();
  53105. }
  53106. this._quaternionToRotationMatrix();
  53107. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  53108. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  53109. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  53110. if (this._copy.translateFromPivot) {
  53111. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  53112. }
  53113. else {
  53114. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  53115. }
  53116. for (i = 0; i < shape.length; i++) {
  53117. this._vertex.x = shape[i].x;
  53118. this._vertex.y = shape[i].y;
  53119. this._vertex.z = shape[i].z;
  53120. if (options && options.vertexFunction) {
  53121. options.vertexFunction(this._copy, this._vertex, i);
  53122. }
  53123. this._vertex.x *= this._copy.scaling.x;
  53124. this._vertex.y *= this._copy.scaling.y;
  53125. this._vertex.z *= this._copy.scaling.z;
  53126. this._vertex.x -= this._scaledPivot.x;
  53127. this._vertex.y -= this._scaledPivot.y;
  53128. this._vertex.z -= this._scaledPivot.z;
  53129. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  53130. this._rotated.addInPlace(this._pivotBackTranslation);
  53131. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  53132. if (meshUV) {
  53133. 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);
  53134. u += 2;
  53135. }
  53136. if (this._copy.color) {
  53137. this._color = this._copy.color;
  53138. }
  53139. else if (meshCol && meshCol[c] !== undefined) {
  53140. this._color.r = meshCol[c];
  53141. this._color.g = meshCol[c + 1];
  53142. this._color.b = meshCol[c + 2];
  53143. this._color.a = meshCol[c + 3];
  53144. }
  53145. else {
  53146. this._color.r = 1.0;
  53147. this._color.g = 1.0;
  53148. this._color.b = 1.0;
  53149. this._color.a = 1.0;
  53150. }
  53151. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  53152. c += 4;
  53153. if (!this.recomputeNormals && meshNor) {
  53154. this._normal.x = meshNor[n];
  53155. this._normal.y = meshNor[n + 1];
  53156. this._normal.z = meshNor[n + 2];
  53157. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  53158. normals.push(this._normal.x, this._normal.y, this._normal.z);
  53159. n += 3;
  53160. }
  53161. }
  53162. for (i = 0; i < meshInd.length; i++) {
  53163. var current_ind = p + meshInd[i];
  53164. indices.push(current_ind);
  53165. if (current_ind > 65535) {
  53166. this._needs32Bits = true;
  53167. }
  53168. }
  53169. if (this._pickable) {
  53170. var nbfaces = meshInd.length / 3;
  53171. for (i = 0; i < nbfaces; i++) {
  53172. this.pickedParticles.push({ idx: idx, faceId: i });
  53173. }
  53174. }
  53175. if (this._depthSort) {
  53176. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  53177. }
  53178. return this._copy;
  53179. };
  53180. // returns a shape array from positions array
  53181. SolidParticleSystem.prototype._posToShape = function (positions) {
  53182. var shape = [];
  53183. for (var i = 0; i < positions.length; i += 3) {
  53184. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  53185. }
  53186. return shape;
  53187. };
  53188. // returns a shapeUV array from a Vector4 uvs
  53189. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  53190. var shapeUV = [];
  53191. if (uvs) {
  53192. for (var i = 0; i < uvs.length; i++)
  53193. shapeUV.push(uvs[i]);
  53194. }
  53195. return shapeUV;
  53196. };
  53197. // adds a new particle object in the particles array
  53198. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  53199. if (bInfo === void 0) { bInfo = null; }
  53200. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  53201. this.particles.push(sp);
  53202. return sp;
  53203. };
  53204. /**
  53205. * Adds some particles to the SPS from the model shape. Returns the shape id.
  53206. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  53207. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  53208. * @param nb (positive integer) the number of particles to be created from this model
  53209. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  53210. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  53211. * @returns the number of shapes in the system
  53212. */
  53213. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  53214. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53215. var meshInd = mesh.getIndices();
  53216. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53217. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53218. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53219. var bbInfo;
  53220. if (this._particlesIntersect) {
  53221. bbInfo = mesh.getBoundingInfo();
  53222. }
  53223. var shape = this._posToShape(meshPos);
  53224. var shapeUV = this._uvsToShapeUV(meshUV);
  53225. var posfunc = options ? options.positionFunction : null;
  53226. var vtxfunc = options ? options.vertexFunction : null;
  53227. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  53228. // particles
  53229. var sp;
  53230. var currentCopy;
  53231. var idx = this.nbParticles;
  53232. for (var i = 0; i < nb; i++) {
  53233. var currentPos = this._positions.length;
  53234. var currentInd = this._indices.length;
  53235. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  53236. if (this._updatable) {
  53237. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  53238. sp.position.copyFrom(currentCopy.position);
  53239. sp.rotation.copyFrom(currentCopy.rotation);
  53240. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  53241. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  53242. }
  53243. if (currentCopy.color && sp.color) {
  53244. sp.color.copyFrom(currentCopy.color);
  53245. }
  53246. sp.scaling.copyFrom(currentCopy.scaling);
  53247. sp.uvs.copyFrom(currentCopy.uvs);
  53248. }
  53249. this._index += shape.length;
  53250. idx++;
  53251. }
  53252. this.nbParticles += nb;
  53253. this._shapeCounter++;
  53254. return this._shapeCounter - 1;
  53255. };
  53256. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  53257. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  53258. this._resetCopy();
  53259. if (particle._model._positionFunction) {
  53260. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  53261. }
  53262. if (this._copy.rotationQuaternion) {
  53263. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  53264. }
  53265. else {
  53266. this._yaw = this._copy.rotation.y;
  53267. this._pitch = this._copy.rotation.x;
  53268. this._roll = this._copy.rotation.z;
  53269. this._quaternionRotationYPR();
  53270. }
  53271. this._quaternionToRotationMatrix();
  53272. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  53273. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  53274. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  53275. if (this._copy.translateFromPivot) {
  53276. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  53277. }
  53278. else {
  53279. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  53280. }
  53281. this._shape = particle._model._shape;
  53282. for (var pt = 0; pt < this._shape.length; pt++) {
  53283. this._vertex.x = this._shape[pt].x;
  53284. this._vertex.y = this._shape[pt].y;
  53285. this._vertex.z = this._shape[pt].z;
  53286. if (particle._model._vertexFunction) {
  53287. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  53288. }
  53289. this._vertex.x *= this._copy.scaling.x;
  53290. this._vertex.y *= this._copy.scaling.y;
  53291. this._vertex.z *= this._copy.scaling.z;
  53292. this._vertex.x -= this._scaledPivot.x;
  53293. this._vertex.y -= this._scaledPivot.y;
  53294. this._vertex.z -= this._scaledPivot.z;
  53295. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  53296. this._rotated.addInPlace(this._pivotBackTranslation);
  53297. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  53298. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  53299. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  53300. }
  53301. particle.position.x = 0.0;
  53302. particle.position.y = 0.0;
  53303. particle.position.z = 0.0;
  53304. particle.rotation.x = 0.0;
  53305. particle.rotation.y = 0.0;
  53306. particle.rotation.z = 0.0;
  53307. particle.rotationQuaternion = null;
  53308. particle.scaling.x = 1.0;
  53309. particle.scaling.y = 1.0;
  53310. particle.scaling.z = 1.0;
  53311. particle.uvs.x = 0.0;
  53312. particle.uvs.y = 0.0;
  53313. particle.uvs.z = 1.0;
  53314. particle.uvs.w = 1.0;
  53315. particle.pivot.x = 0.0;
  53316. particle.pivot.y = 0.0;
  53317. particle.pivot.z = 0.0;
  53318. particle.translateFromPivot = false;
  53319. particle.parentId = null;
  53320. };
  53321. /**
  53322. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  53323. * @returns the SPS.
  53324. */
  53325. SolidParticleSystem.prototype.rebuildMesh = function () {
  53326. for (var p = 0; p < this.particles.length; p++) {
  53327. this._rebuildParticle(this.particles[p]);
  53328. }
  53329. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53330. return this;
  53331. };
  53332. /**
  53333. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  53334. * This method calls `updateParticle()` for each particle of the SPS.
  53335. * For an animated SPS, it is usually called within the render loop.
  53336. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  53337. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  53338. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  53339. * @returns the SPS.
  53340. */
  53341. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  53342. if (start === void 0) { start = 0; }
  53343. if (end === void 0) { end = this.nbParticles - 1; }
  53344. if (update === void 0) { update = true; }
  53345. if (!this._updatable) {
  53346. return this;
  53347. }
  53348. // custom beforeUpdate
  53349. this.beforeUpdateParticles(start, end, update);
  53350. this._cam_axisX.x = 1.0;
  53351. this._cam_axisX.y = 0.0;
  53352. this._cam_axisX.z = 0.0;
  53353. this._cam_axisY.x = 0.0;
  53354. this._cam_axisY.y = 1.0;
  53355. this._cam_axisY.z = 0.0;
  53356. this._cam_axisZ.x = 0.0;
  53357. this._cam_axisZ.y = 0.0;
  53358. this._cam_axisZ.z = 1.0;
  53359. // cases when the World Matrix is to be computed first
  53360. if (this.billboard || this._depthSort) {
  53361. this.mesh.computeWorldMatrix(true);
  53362. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  53363. }
  53364. // if the particles will always face the camera
  53365. if (this.billboard) {
  53366. // compute the camera position and un-rotate it by the current mesh rotation
  53367. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  53368. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  53369. this._cam_axisZ.normalize();
  53370. // same for camera up vector extracted from the cam view matrix
  53371. var view = this._camera.getViewMatrix(true);
  53372. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  53373. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  53374. this._cam_axisY.normalize();
  53375. this._cam_axisX.normalize();
  53376. }
  53377. // if depthSort, compute the camera global position in the mesh local system
  53378. if (this._depthSort) {
  53379. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  53380. }
  53381. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  53382. var idx = 0; // current position index in the global array positions32
  53383. var index = 0; // position start index in the global array positions32 of the current particle
  53384. var colidx = 0; // current color index in the global array colors32
  53385. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  53386. var uvidx = 0; // current uv index in the global array uvs32
  53387. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  53388. var pt = 0; // current index in the particle model shape
  53389. if (this.mesh.isFacetDataEnabled) {
  53390. this._computeBoundingBox = true;
  53391. }
  53392. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  53393. if (this._computeBoundingBox) {
  53394. if (start == 0 && end == this.nbParticles - 1) {
  53395. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  53396. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  53397. }
  53398. else {
  53399. if (this.mesh._boundingInfo) {
  53400. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  53401. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  53402. }
  53403. }
  53404. }
  53405. // particle loop
  53406. index = this.particles[start]._pos;
  53407. var vpos = (index / 3) | 0;
  53408. colorIndex = vpos * 4;
  53409. uvIndex = vpos * 2;
  53410. for (var p = start; p <= end; p++) {
  53411. this._particle = this.particles[p];
  53412. this._shape = this._particle._model._shape;
  53413. this._shapeUV = this._particle._model._shapeUV;
  53414. // call to custom user function to update the particle properties
  53415. this.updateParticle(this._particle);
  53416. // camera-particle distance for depth sorting
  53417. if (this._depthSort && this._depthSortParticles) {
  53418. var dsp = this.depthSortedParticles[p];
  53419. dsp.ind = this._particle._ind;
  53420. dsp.indicesLength = this._particle._model._indicesLength;
  53421. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  53422. }
  53423. // skip the computations for inactive or already invisible particles
  53424. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  53425. // increment indexes for the next particle
  53426. pt = this._shape.length;
  53427. index += pt * 3;
  53428. colorIndex += pt * 4;
  53429. uvIndex += pt * 2;
  53430. continue;
  53431. }
  53432. if (this._particle.isVisible) {
  53433. this._particle._stillInvisible = false; // un-mark permanent invisibility
  53434. this._particleHasParent = (this._particle.parentId !== null);
  53435. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  53436. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  53437. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  53438. // particle rotation matrix
  53439. if (this.billboard) {
  53440. this._particle.rotation.x = 0.0;
  53441. this._particle.rotation.y = 0.0;
  53442. }
  53443. if (this._computeParticleRotation || this.billboard) {
  53444. if (this._particle.rotationQuaternion) {
  53445. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53446. }
  53447. else {
  53448. this._yaw = this._particle.rotation.y;
  53449. this._pitch = this._particle.rotation.x;
  53450. this._roll = this._particle.rotation.z;
  53451. this._quaternionRotationYPR();
  53452. }
  53453. this._quaternionToRotationMatrix();
  53454. }
  53455. if (this._particleHasParent) {
  53456. this._parent = this.particles[this._particle.parentId];
  53457. 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];
  53458. 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];
  53459. 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];
  53460. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  53461. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  53462. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  53463. if (this._computeParticleRotation || this.billboard) {
  53464. 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];
  53465. 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];
  53466. 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];
  53467. 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];
  53468. 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];
  53469. 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];
  53470. 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];
  53471. 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];
  53472. 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];
  53473. }
  53474. }
  53475. else {
  53476. this._particle._globalPosition.x = this._particle.position.x;
  53477. this._particle._globalPosition.y = this._particle.position.y;
  53478. this._particle._globalPosition.z = this._particle.position.z;
  53479. if (this._computeParticleRotation || this.billboard) {
  53480. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  53481. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  53482. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  53483. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  53484. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  53485. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  53486. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  53487. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  53488. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  53489. }
  53490. }
  53491. if (this._particle.translateFromPivot) {
  53492. this._pivotBackTranslation.x = 0.0;
  53493. this._pivotBackTranslation.y = 0.0;
  53494. this._pivotBackTranslation.z = 0.0;
  53495. }
  53496. else {
  53497. this._pivotBackTranslation.x = this._scaledPivot.x;
  53498. this._pivotBackTranslation.y = this._scaledPivot.y;
  53499. this._pivotBackTranslation.z = this._scaledPivot.z;
  53500. }
  53501. // particle vertex loop
  53502. for (pt = 0; pt < this._shape.length; pt++) {
  53503. idx = index + pt * 3;
  53504. colidx = colorIndex + pt * 4;
  53505. uvidx = uvIndex + pt * 2;
  53506. this._vertex.x = this._shape[pt].x;
  53507. this._vertex.y = this._shape[pt].y;
  53508. this._vertex.z = this._shape[pt].z;
  53509. if (this._computeParticleVertex) {
  53510. this.updateParticleVertex(this._particle, this._vertex, pt);
  53511. }
  53512. // positions
  53513. this._vertex.x *= this._particle.scaling.x;
  53514. this._vertex.y *= this._particle.scaling.y;
  53515. this._vertex.z *= this._particle.scaling.z;
  53516. this._vertex.x -= this._scaledPivot.x;
  53517. this._vertex.y -= this._scaledPivot.y;
  53518. this._vertex.z -= this._scaledPivot.z;
  53519. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  53520. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  53521. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  53522. this._rotated.x += this._pivotBackTranslation.x;
  53523. this._rotated.y += this._pivotBackTranslation.y;
  53524. this._rotated.z += this._pivotBackTranslation.z;
  53525. 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;
  53526. 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;
  53527. 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;
  53528. if (this._computeBoundingBox) {
  53529. if (this._positions32[idx] < this._minimum.x) {
  53530. this._minimum.x = this._positions32[idx];
  53531. }
  53532. if (this._positions32[idx] > this._maximum.x) {
  53533. this._maximum.x = this._positions32[idx];
  53534. }
  53535. if (this._positions32[idx + 1] < this._minimum.y) {
  53536. this._minimum.y = this._positions32[idx + 1];
  53537. }
  53538. if (this._positions32[idx + 1] > this._maximum.y) {
  53539. this._maximum.y = this._positions32[idx + 1];
  53540. }
  53541. if (this._positions32[idx + 2] < this._minimum.z) {
  53542. this._minimum.z = this._positions32[idx + 2];
  53543. }
  53544. if (this._positions32[idx + 2] > this._maximum.z) {
  53545. this._maximum.z = this._positions32[idx + 2];
  53546. }
  53547. }
  53548. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  53549. if (!this._computeParticleVertex) {
  53550. this._normal.x = this._fixedNormal32[idx];
  53551. this._normal.y = this._fixedNormal32[idx + 1];
  53552. this._normal.z = this._fixedNormal32[idx + 2];
  53553. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  53554. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  53555. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  53556. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  53557. 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;
  53558. 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;
  53559. }
  53560. if (this._computeParticleColor && this._particle.color) {
  53561. this._colors32[colidx] = this._particle.color.r;
  53562. this._colors32[colidx + 1] = this._particle.color.g;
  53563. this._colors32[colidx + 2] = this._particle.color.b;
  53564. this._colors32[colidx + 3] = this._particle.color.a;
  53565. }
  53566. if (this._computeParticleTexture) {
  53567. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53568. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53569. }
  53570. }
  53571. }
  53572. else {
  53573. this._particle._stillInvisible = true; // mark the particle as invisible
  53574. for (pt = 0; pt < this._shape.length; pt++) {
  53575. idx = index + pt * 3;
  53576. colidx = colorIndex + pt * 4;
  53577. uvidx = uvIndex + pt * 2;
  53578. this._positions32[idx] = 0.0;
  53579. this._positions32[idx + 1] = 0.0;
  53580. this._positions32[idx + 2] = 0.0;
  53581. this._normals32[idx] = 0.0;
  53582. this._normals32[idx + 1] = 0.0;
  53583. this._normals32[idx + 2] = 0.0;
  53584. if (this._computeParticleColor && this._particle.color) {
  53585. this._colors32[colidx] = this._particle.color.r;
  53586. this._colors32[colidx + 1] = this._particle.color.g;
  53587. this._colors32[colidx + 2] = this._particle.color.b;
  53588. this._colors32[colidx + 3] = this._particle.color.a;
  53589. }
  53590. if (this._computeParticleTexture) {
  53591. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53592. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53593. }
  53594. }
  53595. }
  53596. // if the particle intersections must be computed : update the bbInfo
  53597. if (this._particlesIntersect) {
  53598. var bInfo = this._particle._boundingInfo;
  53599. var bBox = bInfo.boundingBox;
  53600. var bSphere = bInfo.boundingSphere;
  53601. if (!this._bSphereOnly) {
  53602. // place, scale and rotate the particle bbox within the SPS local system, then update it
  53603. for (var b = 0; b < bBox.vectors.length; b++) {
  53604. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  53605. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  53606. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  53607. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  53608. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  53609. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  53610. 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;
  53611. 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;
  53612. 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;
  53613. }
  53614. bBox._update(this.mesh._worldMatrix);
  53615. }
  53616. // place and scale the particle bouding sphere in the SPS local system, then update it
  53617. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  53618. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  53619. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  53620. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  53621. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  53622. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  53623. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  53624. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  53625. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  53626. 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));
  53627. bSphere._update(this.mesh._worldMatrix);
  53628. }
  53629. // increment indexes for the next particle
  53630. index = idx + 3;
  53631. colorIndex = colidx + 4;
  53632. uvIndex = uvidx + 2;
  53633. }
  53634. // if the VBO must be updated
  53635. if (update) {
  53636. if (this._computeParticleColor) {
  53637. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  53638. }
  53639. if (this._computeParticleTexture) {
  53640. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  53641. }
  53642. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53643. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  53644. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  53645. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  53646. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  53647. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  53648. for (var i = 0; i < this._normals32.length; i++) {
  53649. this._fixedNormal32[i] = this._normals32[i];
  53650. }
  53651. }
  53652. if (!this.mesh.areNormalsFrozen) {
  53653. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  53654. }
  53655. }
  53656. if (this._depthSort && this._depthSortParticles) {
  53657. this.depthSortedParticles.sort(this._depthSortFunction);
  53658. var dspl = this.depthSortedParticles.length;
  53659. var sorted = 0;
  53660. var lind = 0;
  53661. var sind = 0;
  53662. var sid = 0;
  53663. for (sorted = 0; sorted < dspl; sorted++) {
  53664. lind = this.depthSortedParticles[sorted].indicesLength;
  53665. sind = this.depthSortedParticles[sorted].ind;
  53666. for (var i = 0; i < lind; i++) {
  53667. this._indices32[sid] = this._indices[sind + i];
  53668. sid++;
  53669. }
  53670. }
  53671. this.mesh.updateIndices(this._indices32);
  53672. }
  53673. }
  53674. if (this._computeBoundingBox) {
  53675. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  53676. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  53677. }
  53678. this.afterUpdateParticles(start, end, update);
  53679. return this;
  53680. };
  53681. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  53682. this._halfroll = this._roll * 0.5;
  53683. this._halfpitch = this._pitch * 0.5;
  53684. this._halfyaw = this._yaw * 0.5;
  53685. this._sinRoll = Math.sin(this._halfroll);
  53686. this._cosRoll = Math.cos(this._halfroll);
  53687. this._sinPitch = Math.sin(this._halfpitch);
  53688. this._cosPitch = Math.cos(this._halfpitch);
  53689. this._sinYaw = Math.sin(this._halfyaw);
  53690. this._cosYaw = Math.cos(this._halfyaw);
  53691. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  53692. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  53693. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  53694. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  53695. };
  53696. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  53697. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  53698. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  53699. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  53700. this._rotMatrix.m[3] = 0;
  53701. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  53702. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  53703. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  53704. this._rotMatrix.m[7] = 0;
  53705. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  53706. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  53707. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  53708. this._rotMatrix.m[11] = 0;
  53709. this._rotMatrix.m[12] = 0;
  53710. this._rotMatrix.m[13] = 0;
  53711. this._rotMatrix.m[14] = 0;
  53712. this._rotMatrix.m[15] = 1.0;
  53713. };
  53714. /**
  53715. * Disposes the SPS.
  53716. */
  53717. SolidParticleSystem.prototype.dispose = function () {
  53718. this.mesh.dispose();
  53719. this.vars = null;
  53720. // drop references to internal big arrays for the GC
  53721. this._positions = null;
  53722. this._indices = null;
  53723. this._normals = null;
  53724. this._uvs = null;
  53725. this._colors = null;
  53726. this._indices32 = null;
  53727. this._positions32 = null;
  53728. this._normals32 = null;
  53729. this._fixedNormal32 = null;
  53730. this._uvs32 = null;
  53731. this._colors32 = null;
  53732. this.pickedParticles = null;
  53733. };
  53734. /**
  53735. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  53736. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53737. * @returns the SPS.
  53738. */
  53739. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  53740. if (!this._isVisibilityBoxLocked) {
  53741. this.mesh.refreshBoundingInfo();
  53742. }
  53743. return this;
  53744. };
  53745. /**
  53746. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  53747. * @param size the size (float) of the visibility box
  53748. * note : this doesn't lock the SPS mesh bounding box.
  53749. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53750. */
  53751. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  53752. var vis = size / 2;
  53753. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  53754. };
  53755. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  53756. /**
  53757. * Gets whether the SPS as always visible or not
  53758. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53759. */
  53760. get: function () {
  53761. return this._alwaysVisible;
  53762. },
  53763. /**
  53764. * Sets the SPS as always visible or not
  53765. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53766. */
  53767. set: function (val) {
  53768. this._alwaysVisible = val;
  53769. this.mesh.alwaysSelectAsActiveMesh = val;
  53770. },
  53771. enumerable: true,
  53772. configurable: true
  53773. });
  53774. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  53775. /**
  53776. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  53777. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53778. */
  53779. get: function () {
  53780. return this._isVisibilityBoxLocked;
  53781. },
  53782. /**
  53783. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  53784. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53785. */
  53786. set: function (val) {
  53787. this._isVisibilityBoxLocked = val;
  53788. var boundingInfo = this.mesh.getBoundingInfo();
  53789. boundingInfo.isLocked = val;
  53790. },
  53791. enumerable: true,
  53792. configurable: true
  53793. });
  53794. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  53795. /**
  53796. * Gets if `setParticles()` computes the particle rotations or not.
  53797. * Default value : true. The SPS is faster when it's set to false.
  53798. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  53799. */
  53800. get: function () {
  53801. return this._computeParticleRotation;
  53802. },
  53803. /**
  53804. * Tells to `setParticles()` to compute the particle rotations or not.
  53805. * Default value : true. The SPS is faster when it's set to false.
  53806. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  53807. */
  53808. set: function (val) {
  53809. this._computeParticleRotation = val;
  53810. },
  53811. enumerable: true,
  53812. configurable: true
  53813. });
  53814. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  53815. /**
  53816. * Gets if `setParticles()` computes the particle colors or not.
  53817. * Default value : true. The SPS is faster when it's set to false.
  53818. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  53819. */
  53820. get: function () {
  53821. return this._computeParticleColor;
  53822. },
  53823. /**
  53824. * Tells to `setParticles()` to compute the particle colors or not.
  53825. * Default value : true. The SPS is faster when it's set to false.
  53826. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  53827. */
  53828. set: function (val) {
  53829. this._computeParticleColor = val;
  53830. },
  53831. enumerable: true,
  53832. configurable: true
  53833. });
  53834. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  53835. /**
  53836. * Gets if `setParticles()` computes the particle textures or not.
  53837. * Default value : true. The SPS is faster when it's set to false.
  53838. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  53839. */
  53840. get: function () {
  53841. return this._computeParticleTexture;
  53842. },
  53843. set: function (val) {
  53844. this._computeParticleTexture = val;
  53845. },
  53846. enumerable: true,
  53847. configurable: true
  53848. });
  53849. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  53850. /**
  53851. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  53852. * Default value : false. The SPS is faster when it's set to false.
  53853. * Note : the particle custom vertex positions aren't stored values.
  53854. */
  53855. get: function () {
  53856. return this._computeParticleVertex;
  53857. },
  53858. /**
  53859. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  53860. * Default value : false. The SPS is faster when it's set to false.
  53861. * Note : the particle custom vertex positions aren't stored values.
  53862. */
  53863. set: function (val) {
  53864. this._computeParticleVertex = val;
  53865. },
  53866. enumerable: true,
  53867. configurable: true
  53868. });
  53869. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  53870. /**
  53871. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  53872. */
  53873. get: function () {
  53874. return this._computeBoundingBox;
  53875. },
  53876. /**
  53877. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  53878. */
  53879. set: function (val) {
  53880. this._computeBoundingBox = val;
  53881. },
  53882. enumerable: true,
  53883. configurable: true
  53884. });
  53885. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  53886. /**
  53887. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  53888. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  53889. * Default : `true`
  53890. */
  53891. get: function () {
  53892. return this._depthSortParticles;
  53893. },
  53894. /**
  53895. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  53896. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  53897. * Default : `true`
  53898. */
  53899. set: function (val) {
  53900. this._depthSortParticles = val;
  53901. },
  53902. enumerable: true,
  53903. configurable: true
  53904. });
  53905. // =======================================================================
  53906. // Particle behavior logic
  53907. // these following methods may be overwritten by the user to fit his needs
  53908. /**
  53909. * This function does nothing. It may be overwritten to set all the particle first values.
  53910. * The SPS doesn't call this function, you may have to call it by your own.
  53911. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53912. */
  53913. SolidParticleSystem.prototype.initParticles = function () {
  53914. };
  53915. /**
  53916. * This function does nothing. It may be overwritten to recycle a particle.
  53917. * The SPS doesn't call this function, you may have to call it by your own.
  53918. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53919. * @param particle The particle to recycle
  53920. * @returns the recycled particle
  53921. */
  53922. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  53923. return particle;
  53924. };
  53925. /**
  53926. * Updates a particle : this function should be overwritten by the user.
  53927. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  53928. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53929. * @example : just set a particle position or velocity and recycle conditions
  53930. * @param particle The particle to update
  53931. * @returns the updated particle
  53932. */
  53933. SolidParticleSystem.prototype.updateParticle = function (particle) {
  53934. return particle;
  53935. };
  53936. /**
  53937. * Updates a vertex of a particle : it can be overwritten by the user.
  53938. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  53939. * @param particle the current particle
  53940. * @param vertex the current index of the current particle
  53941. * @param pt the index of the current vertex in the particle shape
  53942. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  53943. * @example : just set a vertex particle position
  53944. * @returns the updated vertex
  53945. */
  53946. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  53947. return vertex;
  53948. };
  53949. /**
  53950. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  53951. * This does nothing and may be overwritten by the user.
  53952. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53953. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53954. * @param update the boolean update value actually passed to setParticles()
  53955. */
  53956. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  53957. };
  53958. /**
  53959. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  53960. * This will be passed three parameters.
  53961. * This does nothing and may be overwritten by the user.
  53962. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53963. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53964. * @param update the boolean update value actually passed to setParticles()
  53965. */
  53966. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  53967. };
  53968. return SolidParticleSystem;
  53969. }());
  53970. BABYLON.SolidParticleSystem = SolidParticleSystem;
  53971. })(BABYLON || (BABYLON = {}));
  53972. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  53973. var BABYLON;
  53974. (function (BABYLON) {
  53975. var ShaderMaterial = /** @class */ (function (_super) {
  53976. __extends(ShaderMaterial, _super);
  53977. function ShaderMaterial(name, scene, shaderPath, options) {
  53978. var _this = _super.call(this, name, scene) || this;
  53979. _this._textures = {};
  53980. _this._textureArrays = {};
  53981. _this._floats = {};
  53982. _this._ints = {};
  53983. _this._floatsArrays = {};
  53984. _this._colors3 = {};
  53985. _this._colors3Arrays = {};
  53986. _this._colors4 = {};
  53987. _this._vectors2 = {};
  53988. _this._vectors3 = {};
  53989. _this._vectors4 = {};
  53990. _this._matrices = {};
  53991. _this._matrices3x3 = {};
  53992. _this._matrices2x2 = {};
  53993. _this._vectors2Arrays = {};
  53994. _this._vectors3Arrays = {};
  53995. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  53996. _this._shaderPath = shaderPath;
  53997. options.needAlphaBlending = options.needAlphaBlending || false;
  53998. options.needAlphaTesting = options.needAlphaTesting || false;
  53999. options.attributes = options.attributes || ["position", "normal", "uv"];
  54000. options.uniforms = options.uniforms || ["worldViewProjection"];
  54001. options.uniformBuffers = options.uniformBuffers || [];
  54002. options.samplers = options.samplers || [];
  54003. options.defines = options.defines || [];
  54004. _this._options = options;
  54005. return _this;
  54006. }
  54007. ShaderMaterial.prototype.getClassName = function () {
  54008. return "ShaderMaterial";
  54009. };
  54010. ShaderMaterial.prototype.needAlphaBlending = function () {
  54011. return this._options.needAlphaBlending;
  54012. };
  54013. ShaderMaterial.prototype.needAlphaTesting = function () {
  54014. return this._options.needAlphaTesting;
  54015. };
  54016. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  54017. if (this._options.uniforms.indexOf(uniformName) === -1) {
  54018. this._options.uniforms.push(uniformName);
  54019. }
  54020. };
  54021. ShaderMaterial.prototype.setTexture = function (name, texture) {
  54022. if (this._options.samplers.indexOf(name) === -1) {
  54023. this._options.samplers.push(name);
  54024. }
  54025. this._textures[name] = texture;
  54026. return this;
  54027. };
  54028. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  54029. if (this._options.samplers.indexOf(name) === -1) {
  54030. this._options.samplers.push(name);
  54031. }
  54032. this._checkUniform(name);
  54033. this._textureArrays[name] = textures;
  54034. return this;
  54035. };
  54036. ShaderMaterial.prototype.setFloat = function (name, value) {
  54037. this._checkUniform(name);
  54038. this._floats[name] = value;
  54039. return this;
  54040. };
  54041. ShaderMaterial.prototype.setInt = function (name, value) {
  54042. this._checkUniform(name);
  54043. this._ints[name] = value;
  54044. return this;
  54045. };
  54046. ShaderMaterial.prototype.setFloats = function (name, value) {
  54047. this._checkUniform(name);
  54048. this._floatsArrays[name] = value;
  54049. return this;
  54050. };
  54051. ShaderMaterial.prototype.setColor3 = function (name, value) {
  54052. this._checkUniform(name);
  54053. this._colors3[name] = value;
  54054. return this;
  54055. };
  54056. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  54057. this._checkUniform(name);
  54058. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  54059. color.toArray(arr, arr.length);
  54060. return arr;
  54061. }, []);
  54062. return this;
  54063. };
  54064. ShaderMaterial.prototype.setColor4 = function (name, value) {
  54065. this._checkUniform(name);
  54066. this._colors4[name] = value;
  54067. return this;
  54068. };
  54069. ShaderMaterial.prototype.setVector2 = function (name, value) {
  54070. this._checkUniform(name);
  54071. this._vectors2[name] = value;
  54072. return this;
  54073. };
  54074. ShaderMaterial.prototype.setVector3 = function (name, value) {
  54075. this._checkUniform(name);
  54076. this._vectors3[name] = value;
  54077. return this;
  54078. };
  54079. ShaderMaterial.prototype.setVector4 = function (name, value) {
  54080. this._checkUniform(name);
  54081. this._vectors4[name] = value;
  54082. return this;
  54083. };
  54084. ShaderMaterial.prototype.setMatrix = function (name, value) {
  54085. this._checkUniform(name);
  54086. this._matrices[name] = value;
  54087. return this;
  54088. };
  54089. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  54090. this._checkUniform(name);
  54091. this._matrices3x3[name] = value;
  54092. return this;
  54093. };
  54094. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  54095. this._checkUniform(name);
  54096. this._matrices2x2[name] = value;
  54097. return this;
  54098. };
  54099. ShaderMaterial.prototype.setArray2 = function (name, value) {
  54100. this._checkUniform(name);
  54101. this._vectors2Arrays[name] = value;
  54102. return this;
  54103. };
  54104. ShaderMaterial.prototype.setArray3 = function (name, value) {
  54105. this._checkUniform(name);
  54106. this._vectors3Arrays[name] = value;
  54107. return this;
  54108. };
  54109. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  54110. if (!mesh) {
  54111. return true;
  54112. }
  54113. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  54114. return false;
  54115. }
  54116. return false;
  54117. };
  54118. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  54119. var scene = this.getScene();
  54120. var engine = scene.getEngine();
  54121. if (!this.checkReadyOnEveryCall) {
  54122. if (this._renderId === scene.getRenderId()) {
  54123. if (this._checkCache(scene, mesh, useInstances)) {
  54124. return true;
  54125. }
  54126. }
  54127. }
  54128. // Instances
  54129. var defines = [];
  54130. var attribs = [];
  54131. var fallbacks = new BABYLON.EffectFallbacks();
  54132. if (useInstances) {
  54133. defines.push("#define INSTANCES");
  54134. }
  54135. for (var index = 0; index < this._options.defines.length; index++) {
  54136. defines.push(this._options.defines[index]);
  54137. }
  54138. for (var index = 0; index < this._options.attributes.length; index++) {
  54139. attribs.push(this._options.attributes[index]);
  54140. }
  54141. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  54142. attribs.push(BABYLON.VertexBuffer.ColorKind);
  54143. defines.push("#define VERTEXCOLOR");
  54144. }
  54145. // Bones
  54146. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  54147. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  54148. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  54149. if (mesh.numBoneInfluencers > 4) {
  54150. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  54151. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  54152. }
  54153. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  54154. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  54155. fallbacks.addCPUSkinningFallback(0, mesh);
  54156. if (this._options.uniforms.indexOf("mBones") === -1) {
  54157. this._options.uniforms.push("mBones");
  54158. }
  54159. }
  54160. else {
  54161. defines.push("#define NUM_BONE_INFLUENCERS 0");
  54162. }
  54163. // Textures
  54164. for (var name in this._textures) {
  54165. if (!this._textures[name].isReady()) {
  54166. return false;
  54167. }
  54168. }
  54169. // Alpha test
  54170. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  54171. defines.push("#define ALPHATEST");
  54172. }
  54173. var previousEffect = this._effect;
  54174. var join = defines.join("\n");
  54175. this._effect = engine.createEffect(this._shaderPath, {
  54176. attributes: attribs,
  54177. uniformsNames: this._options.uniforms,
  54178. uniformBuffersNames: this._options.uniformBuffers,
  54179. samplers: this._options.samplers,
  54180. defines: join,
  54181. fallbacks: fallbacks,
  54182. onCompiled: this.onCompiled,
  54183. onError: this.onError
  54184. }, engine);
  54185. if (!this._effect.isReady()) {
  54186. return false;
  54187. }
  54188. if (previousEffect !== this._effect) {
  54189. scene.resetCachedMaterial();
  54190. }
  54191. this._renderId = scene.getRenderId();
  54192. return true;
  54193. };
  54194. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  54195. var scene = this.getScene();
  54196. if (!this._effect) {
  54197. return;
  54198. }
  54199. if (this._options.uniforms.indexOf("world") !== -1) {
  54200. this._effect.setMatrix("world", world);
  54201. }
  54202. if (this._options.uniforms.indexOf("worldView") !== -1) {
  54203. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  54204. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  54205. }
  54206. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  54207. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  54208. }
  54209. };
  54210. ShaderMaterial.prototype.bind = function (world, mesh) {
  54211. // Std values
  54212. this.bindOnlyWorldMatrix(world);
  54213. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  54214. if (this._options.uniforms.indexOf("view") !== -1) {
  54215. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  54216. }
  54217. if (this._options.uniforms.indexOf("projection") !== -1) {
  54218. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  54219. }
  54220. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  54221. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  54222. }
  54223. // Bones
  54224. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  54225. var name;
  54226. // Texture
  54227. for (name in this._textures) {
  54228. this._effect.setTexture(name, this._textures[name]);
  54229. }
  54230. // Texture arrays
  54231. for (name in this._textureArrays) {
  54232. this._effect.setTextureArray(name, this._textureArrays[name]);
  54233. }
  54234. // Int
  54235. for (name in this._ints) {
  54236. this._effect.setInt(name, this._ints[name]);
  54237. }
  54238. // Float
  54239. for (name in this._floats) {
  54240. this._effect.setFloat(name, this._floats[name]);
  54241. }
  54242. // Floats
  54243. for (name in this._floatsArrays) {
  54244. this._effect.setArray(name, this._floatsArrays[name]);
  54245. }
  54246. // Color3
  54247. for (name in this._colors3) {
  54248. this._effect.setColor3(name, this._colors3[name]);
  54249. }
  54250. for (name in this._colors3Arrays) {
  54251. this._effect.setArray3(name, this._colors3Arrays[name]);
  54252. }
  54253. // Color4
  54254. for (name in this._colors4) {
  54255. var color = this._colors4[name];
  54256. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  54257. }
  54258. // Vector2
  54259. for (name in this._vectors2) {
  54260. this._effect.setVector2(name, this._vectors2[name]);
  54261. }
  54262. // Vector3
  54263. for (name in this._vectors3) {
  54264. this._effect.setVector3(name, this._vectors3[name]);
  54265. }
  54266. // Vector4
  54267. for (name in this._vectors4) {
  54268. this._effect.setVector4(name, this._vectors4[name]);
  54269. }
  54270. // Matrix
  54271. for (name in this._matrices) {
  54272. this._effect.setMatrix(name, this._matrices[name]);
  54273. }
  54274. // Matrix 3x3
  54275. for (name in this._matrices3x3) {
  54276. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  54277. }
  54278. // Matrix 2x2
  54279. for (name in this._matrices2x2) {
  54280. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  54281. }
  54282. // Vector2Array
  54283. for (name in this._vectors2Arrays) {
  54284. this._effect.setArray2(name, this._vectors2Arrays[name]);
  54285. }
  54286. // Vector3Array
  54287. for (name in this._vectors3Arrays) {
  54288. this._effect.setArray3(name, this._vectors3Arrays[name]);
  54289. }
  54290. }
  54291. this._afterBind(mesh);
  54292. };
  54293. ShaderMaterial.prototype.getActiveTextures = function () {
  54294. var activeTextures = _super.prototype.getActiveTextures.call(this);
  54295. for (var name in this._textures) {
  54296. activeTextures.push(this._textures[name]);
  54297. }
  54298. for (var name in this._textureArrays) {
  54299. var array = this._textureArrays[name];
  54300. for (var index = 0; index < array.length; index++) {
  54301. activeTextures.push(array[index]);
  54302. }
  54303. }
  54304. return activeTextures;
  54305. };
  54306. ShaderMaterial.prototype.hasTexture = function (texture) {
  54307. if (_super.prototype.hasTexture.call(this, texture)) {
  54308. return true;
  54309. }
  54310. for (var name in this._textures) {
  54311. if (this._textures[name] === texture) {
  54312. return true;
  54313. }
  54314. }
  54315. for (var name in this._textureArrays) {
  54316. var array = this._textureArrays[name];
  54317. for (var index = 0; index < array.length; index++) {
  54318. if (array[index] === texture) {
  54319. return true;
  54320. }
  54321. }
  54322. }
  54323. return false;
  54324. };
  54325. ShaderMaterial.prototype.clone = function (name) {
  54326. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  54327. return newShaderMaterial;
  54328. };
  54329. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  54330. if (forceDisposeTextures) {
  54331. var name;
  54332. for (name in this._textures) {
  54333. this._textures[name].dispose();
  54334. }
  54335. for (name in this._textureArrays) {
  54336. var array = this._textureArrays[name];
  54337. for (var index = 0; index < array.length; index++) {
  54338. array[index].dispose();
  54339. }
  54340. }
  54341. }
  54342. this._textures = {};
  54343. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  54344. };
  54345. ShaderMaterial.prototype.serialize = function () {
  54346. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  54347. serializationObject.customType = "BABYLON.ShaderMaterial";
  54348. serializationObject.options = this._options;
  54349. serializationObject.shaderPath = this._shaderPath;
  54350. var name;
  54351. // Texture
  54352. serializationObject.textures = {};
  54353. for (name in this._textures) {
  54354. serializationObject.textures[name] = this._textures[name].serialize();
  54355. }
  54356. // Texture arrays
  54357. serializationObject.textureArrays = {};
  54358. for (name in this._textureArrays) {
  54359. serializationObject.textureArrays[name] = [];
  54360. var array = this._textureArrays[name];
  54361. for (var index = 0; index < array.length; index++) {
  54362. serializationObject.textureArrays[name].push(array[index].serialize());
  54363. }
  54364. }
  54365. // Float
  54366. serializationObject.floats = {};
  54367. for (name in this._floats) {
  54368. serializationObject.floats[name] = this._floats[name];
  54369. }
  54370. // Float s
  54371. serializationObject.FloatArrays = {};
  54372. for (name in this._floatsArrays) {
  54373. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  54374. }
  54375. // Color3
  54376. serializationObject.colors3 = {};
  54377. for (name in this._colors3) {
  54378. serializationObject.colors3[name] = this._colors3[name].asArray();
  54379. }
  54380. // Color3 array
  54381. serializationObject.colors3Arrays = {};
  54382. for (name in this._colors3Arrays) {
  54383. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  54384. }
  54385. // Color4
  54386. serializationObject.colors4 = {};
  54387. for (name in this._colors4) {
  54388. serializationObject.colors4[name] = this._colors4[name].asArray();
  54389. }
  54390. // Vector2
  54391. serializationObject.vectors2 = {};
  54392. for (name in this._vectors2) {
  54393. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  54394. }
  54395. // Vector3
  54396. serializationObject.vectors3 = {};
  54397. for (name in this._vectors3) {
  54398. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  54399. }
  54400. // Vector4
  54401. serializationObject.vectors4 = {};
  54402. for (name in this._vectors4) {
  54403. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  54404. }
  54405. // Matrix
  54406. serializationObject.matrices = {};
  54407. for (name in this._matrices) {
  54408. serializationObject.matrices[name] = this._matrices[name].asArray();
  54409. }
  54410. // Matrix 3x3
  54411. serializationObject.matrices3x3 = {};
  54412. for (name in this._matrices3x3) {
  54413. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  54414. }
  54415. // Matrix 2x2
  54416. serializationObject.matrices2x2 = {};
  54417. for (name in this._matrices2x2) {
  54418. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  54419. }
  54420. // Vector2Array
  54421. serializationObject.vectors2Arrays = {};
  54422. for (name in this._vectors2Arrays) {
  54423. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  54424. }
  54425. // Vector3Array
  54426. serializationObject.vectors3Arrays = {};
  54427. for (name in this._vectors3Arrays) {
  54428. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  54429. }
  54430. return serializationObject;
  54431. };
  54432. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  54433. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  54434. var name;
  54435. // Texture
  54436. for (name in source.textures) {
  54437. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  54438. }
  54439. // Texture arrays
  54440. for (name in source.textureArrays) {
  54441. var array = source.textureArrays[name];
  54442. var textureArray = new Array();
  54443. for (var index = 0; index < array.length; index++) {
  54444. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  54445. }
  54446. material.setTextureArray(name, textureArray);
  54447. }
  54448. // Float
  54449. for (name in source.floats) {
  54450. material.setFloat(name, source.floats[name]);
  54451. }
  54452. // Float s
  54453. for (name in source.floatsArrays) {
  54454. material.setFloats(name, source.floatsArrays[name]);
  54455. }
  54456. // Color3
  54457. for (name in source.colors3) {
  54458. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  54459. }
  54460. // Color3 arrays
  54461. for (name in source.colors3Arrays) {
  54462. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  54463. if (i % 3 === 0) {
  54464. arr.push([num]);
  54465. }
  54466. else {
  54467. arr[arr.length - 1].push(num);
  54468. }
  54469. return arr;
  54470. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  54471. material.setColor3Array(name, colors);
  54472. }
  54473. // Color4
  54474. for (name in source.colors4) {
  54475. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  54476. }
  54477. // Vector2
  54478. for (name in source.vectors2) {
  54479. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  54480. }
  54481. // Vector3
  54482. for (name in source.vectors3) {
  54483. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  54484. }
  54485. // Vector4
  54486. for (name in source.vectors4) {
  54487. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  54488. }
  54489. // Matrix
  54490. for (name in source.matrices) {
  54491. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  54492. }
  54493. // Matrix 3x3
  54494. for (name in source.matrices3x3) {
  54495. material.setMatrix3x3(name, source.matrices3x3[name]);
  54496. }
  54497. // Matrix 2x2
  54498. for (name in source.matrices2x2) {
  54499. material.setMatrix2x2(name, source.matrices2x2[name]);
  54500. }
  54501. // Vector2Array
  54502. for (name in source.vectors2Arrays) {
  54503. material.setArray2(name, source.vectors2Arrays[name]);
  54504. }
  54505. // Vector3Array
  54506. for (name in source.vectors3Arrays) {
  54507. material.setArray3(name, source.vectors3Arrays[name]);
  54508. }
  54509. return material;
  54510. };
  54511. return ShaderMaterial;
  54512. }(BABYLON.Material));
  54513. BABYLON.ShaderMaterial = ShaderMaterial;
  54514. })(BABYLON || (BABYLON = {}));
  54515. //# sourceMappingURL=babylon.shaderMaterial.js.map
  54516. var BABYLON;
  54517. (function (BABYLON) {
  54518. var GroundMesh = /** @class */ (function (_super) {
  54519. __extends(GroundMesh, _super);
  54520. function GroundMesh(name, scene) {
  54521. var _this = _super.call(this, name, scene) || this;
  54522. _this.generateOctree = false;
  54523. return _this;
  54524. }
  54525. GroundMesh.prototype.getClassName = function () {
  54526. return "GroundMesh";
  54527. };
  54528. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  54529. get: function () {
  54530. return Math.min(this._subdivisionsX, this._subdivisionsY);
  54531. },
  54532. enumerable: true,
  54533. configurable: true
  54534. });
  54535. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  54536. get: function () {
  54537. return this._subdivisionsX;
  54538. },
  54539. enumerable: true,
  54540. configurable: true
  54541. });
  54542. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  54543. get: function () {
  54544. return this._subdivisionsY;
  54545. },
  54546. enumerable: true,
  54547. configurable: true
  54548. });
  54549. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  54550. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  54551. this._subdivisionsX = chunksCount;
  54552. this._subdivisionsY = chunksCount;
  54553. this.subdivide(chunksCount);
  54554. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  54555. };
  54556. /**
  54557. * Returns a height (y) value in the Worl system :
  54558. * the ground altitude at the coordinates (x, z) expressed in the World system.
  54559. * Returns the ground y position if (x, z) are outside the ground surface.
  54560. */
  54561. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  54562. var world = this.getWorldMatrix();
  54563. var invMat = BABYLON.Tmp.Matrix[5];
  54564. world.invertToRef(invMat);
  54565. var tmpVect = BABYLON.Tmp.Vector3[8];
  54566. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  54567. x = tmpVect.x;
  54568. z = tmpVect.z;
  54569. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54570. return this.position.y;
  54571. }
  54572. if (!this._heightQuads || this._heightQuads.length == 0) {
  54573. this._initHeightQuads();
  54574. this._computeHeightQuads();
  54575. }
  54576. var facet = this._getFacetAt(x, z);
  54577. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  54578. // return y in the World system
  54579. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  54580. return tmpVect.y;
  54581. };
  54582. /**
  54583. * Returns a normalized vector (Vector3) orthogonal to the ground
  54584. * at the ground coordinates (x, z) expressed in the World system.
  54585. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  54586. */
  54587. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  54588. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  54589. this.getNormalAtCoordinatesToRef(x, z, normal);
  54590. return normal;
  54591. };
  54592. /**
  54593. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  54594. * at the ground coordinates (x, z) expressed in the World system.
  54595. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  54596. * Returns the GroundMesh.
  54597. */
  54598. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  54599. var world = this.getWorldMatrix();
  54600. var tmpMat = BABYLON.Tmp.Matrix[5];
  54601. world.invertToRef(tmpMat);
  54602. var tmpVect = BABYLON.Tmp.Vector3[8];
  54603. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  54604. x = tmpVect.x;
  54605. z = tmpVect.z;
  54606. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54607. return this;
  54608. }
  54609. if (!this._heightQuads || this._heightQuads.length == 0) {
  54610. this._initHeightQuads();
  54611. this._computeHeightQuads();
  54612. }
  54613. var facet = this._getFacetAt(x, z);
  54614. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  54615. return this;
  54616. };
  54617. /**
  54618. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  54619. * if the ground has been updated.
  54620. * This can be used in the render loop.
  54621. * Returns the GroundMesh.
  54622. */
  54623. GroundMesh.prototype.updateCoordinateHeights = function () {
  54624. if (!this._heightQuads || this._heightQuads.length == 0) {
  54625. this._initHeightQuads();
  54626. }
  54627. this._computeHeightQuads();
  54628. return this;
  54629. };
  54630. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  54631. GroundMesh.prototype._getFacetAt = function (x, z) {
  54632. // retrieve col and row from x, z coordinates in the ground local system
  54633. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  54634. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  54635. var quad = this._heightQuads[row * this._subdivisionsX + col];
  54636. var facet;
  54637. if (z < quad.slope.x * x + quad.slope.y) {
  54638. facet = quad.facet1;
  54639. }
  54640. else {
  54641. facet = quad.facet2;
  54642. }
  54643. return facet;
  54644. };
  54645. // Creates and populates the heightMap array with "facet" elements :
  54646. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  54647. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  54648. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  54649. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  54650. // Returns the GroundMesh.
  54651. GroundMesh.prototype._initHeightQuads = function () {
  54652. var subdivisionsX = this._subdivisionsX;
  54653. var subdivisionsY = this._subdivisionsY;
  54654. this._heightQuads = new Array();
  54655. for (var row = 0; row < subdivisionsY; row++) {
  54656. for (var col = 0; col < subdivisionsX; col++) {
  54657. 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) };
  54658. this._heightQuads[row * subdivisionsX + col] = quad;
  54659. }
  54660. }
  54661. return this;
  54662. };
  54663. // Compute each quad element values and update the the heightMap array :
  54664. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  54665. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  54666. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  54667. // Returns the GroundMesh.
  54668. GroundMesh.prototype._computeHeightQuads = function () {
  54669. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54670. if (!positions) {
  54671. return this;
  54672. }
  54673. var v1 = BABYLON.Tmp.Vector3[3];
  54674. var v2 = BABYLON.Tmp.Vector3[2];
  54675. var v3 = BABYLON.Tmp.Vector3[1];
  54676. var v4 = BABYLON.Tmp.Vector3[0];
  54677. var v1v2 = BABYLON.Tmp.Vector3[4];
  54678. var v1v3 = BABYLON.Tmp.Vector3[5];
  54679. var v1v4 = BABYLON.Tmp.Vector3[6];
  54680. var norm1 = BABYLON.Tmp.Vector3[7];
  54681. var norm2 = BABYLON.Tmp.Vector3[8];
  54682. var i = 0;
  54683. var j = 0;
  54684. var k = 0;
  54685. var cd = 0; // 2D slope coefficient : z = cd * x + h
  54686. var h = 0;
  54687. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  54688. var d2 = 0;
  54689. var subdivisionsX = this._subdivisionsX;
  54690. var subdivisionsY = this._subdivisionsY;
  54691. for (var row = 0; row < subdivisionsY; row++) {
  54692. for (var col = 0; col < subdivisionsX; col++) {
  54693. i = col * 3;
  54694. j = row * (subdivisionsX + 1) * 3;
  54695. k = (row + 1) * (subdivisionsX + 1) * 3;
  54696. v1.x = positions[j + i];
  54697. v1.y = positions[j + i + 1];
  54698. v1.z = positions[j + i + 2];
  54699. v2.x = positions[j + i + 3];
  54700. v2.y = positions[j + i + 4];
  54701. v2.z = positions[j + i + 5];
  54702. v3.x = positions[k + i];
  54703. v3.y = positions[k + i + 1];
  54704. v3.z = positions[k + i + 2];
  54705. v4.x = positions[k + i + 3];
  54706. v4.y = positions[k + i + 4];
  54707. v4.z = positions[k + i + 5];
  54708. // 2D slope V1V4
  54709. cd = (v4.z - v1.z) / (v4.x - v1.x);
  54710. h = v1.z - cd * v1.x; // v1 belongs to the slope
  54711. // facet equations :
  54712. // we compute each facet normal vector
  54713. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  54714. // we compute the value d by applying the equation to v1 which belongs to the plane
  54715. // then we store the facet equation in a Vector4
  54716. v2.subtractToRef(v1, v1v2);
  54717. v3.subtractToRef(v1, v1v3);
  54718. v4.subtractToRef(v1, v1v4);
  54719. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  54720. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  54721. norm1.normalize();
  54722. norm2.normalize();
  54723. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  54724. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  54725. var quad = this._heightQuads[row * subdivisionsX + col];
  54726. quad.slope.copyFromFloats(cd, h);
  54727. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  54728. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  54729. }
  54730. }
  54731. return this;
  54732. };
  54733. GroundMesh.prototype.serialize = function (serializationObject) {
  54734. _super.prototype.serialize.call(this, serializationObject);
  54735. serializationObject.subdivisionsX = this._subdivisionsX;
  54736. serializationObject.subdivisionsY = this._subdivisionsY;
  54737. serializationObject.minX = this._minX;
  54738. serializationObject.maxX = this._maxX;
  54739. serializationObject.minZ = this._minZ;
  54740. serializationObject.maxZ = this._maxZ;
  54741. serializationObject.width = this._width;
  54742. serializationObject.height = this._height;
  54743. };
  54744. GroundMesh.Parse = function (parsedMesh, scene) {
  54745. var result = new GroundMesh(parsedMesh.name, scene);
  54746. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  54747. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  54748. result._minX = parsedMesh.minX;
  54749. result._maxX = parsedMesh.maxX;
  54750. result._minZ = parsedMesh.minZ;
  54751. result._maxZ = parsedMesh.maxZ;
  54752. result._width = parsedMesh.width;
  54753. result._height = parsedMesh.height;
  54754. return result;
  54755. };
  54756. return GroundMesh;
  54757. }(BABYLON.Mesh));
  54758. BABYLON.GroundMesh = GroundMesh;
  54759. })(BABYLON || (BABYLON = {}));
  54760. //# sourceMappingURL=babylon.groundMesh.js.map
  54761. var BABYLON;
  54762. (function (BABYLON) {
  54763. /**
  54764. * Creates an instance based on a source mesh.
  54765. */
  54766. var InstancedMesh = /** @class */ (function (_super) {
  54767. __extends(InstancedMesh, _super);
  54768. function InstancedMesh(name, source) {
  54769. var _this = _super.call(this, name, source.getScene()) || this;
  54770. source.instances.push(_this);
  54771. _this._sourceMesh = source;
  54772. _this.position.copyFrom(source.position);
  54773. _this.rotation.copyFrom(source.rotation);
  54774. _this.scaling.copyFrom(source.scaling);
  54775. if (source.rotationQuaternion) {
  54776. _this.rotationQuaternion = source.rotationQuaternion.clone();
  54777. }
  54778. _this.infiniteDistance = source.infiniteDistance;
  54779. _this.setPivotMatrix(source.getPivotMatrix());
  54780. _this.refreshBoundingInfo();
  54781. _this._syncSubMeshes();
  54782. return _this;
  54783. }
  54784. /**
  54785. * Returns the string "InstancedMesh".
  54786. */
  54787. InstancedMesh.prototype.getClassName = function () {
  54788. return "InstancedMesh";
  54789. };
  54790. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  54791. // Methods
  54792. get: function () {
  54793. return this._sourceMesh.receiveShadows;
  54794. },
  54795. enumerable: true,
  54796. configurable: true
  54797. });
  54798. Object.defineProperty(InstancedMesh.prototype, "material", {
  54799. get: function () {
  54800. return this._sourceMesh.material;
  54801. },
  54802. enumerable: true,
  54803. configurable: true
  54804. });
  54805. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  54806. get: function () {
  54807. return this._sourceMesh.visibility;
  54808. },
  54809. enumerable: true,
  54810. configurable: true
  54811. });
  54812. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  54813. get: function () {
  54814. return this._sourceMesh.skeleton;
  54815. },
  54816. enumerable: true,
  54817. configurable: true
  54818. });
  54819. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  54820. get: function () {
  54821. return this._sourceMesh.renderingGroupId;
  54822. },
  54823. enumerable: true,
  54824. configurable: true
  54825. });
  54826. /**
  54827. * Returns the total number of vertices (integer).
  54828. */
  54829. InstancedMesh.prototype.getTotalVertices = function () {
  54830. return this._sourceMesh.getTotalVertices();
  54831. };
  54832. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  54833. get: function () {
  54834. return this._sourceMesh;
  54835. },
  54836. enumerable: true,
  54837. configurable: true
  54838. });
  54839. /**
  54840. * Is this node ready to be used/rendered
  54841. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  54842. * @return {boolean} is it ready
  54843. */
  54844. InstancedMesh.prototype.isReady = function (completeCheck) {
  54845. if (completeCheck === void 0) { completeCheck = false; }
  54846. return this._sourceMesh.isReady(completeCheck, true);
  54847. };
  54848. /**
  54849. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  54850. */
  54851. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  54852. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  54853. };
  54854. /**
  54855. * Sets the vertex data of the mesh geometry for the requested `kind`.
  54856. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  54857. * The `data` are either a numeric array either a Float32Array.
  54858. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  54859. * 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).
  54860. * Note that a new underlying VertexBuffer object is created each call.
  54861. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  54862. *
  54863. * Possible `kind` values :
  54864. * - BABYLON.VertexBuffer.PositionKind
  54865. * - BABYLON.VertexBuffer.UVKind
  54866. * - BABYLON.VertexBuffer.UV2Kind
  54867. * - BABYLON.VertexBuffer.UV3Kind
  54868. * - BABYLON.VertexBuffer.UV4Kind
  54869. * - BABYLON.VertexBuffer.UV5Kind
  54870. * - BABYLON.VertexBuffer.UV6Kind
  54871. * - BABYLON.VertexBuffer.ColorKind
  54872. * - BABYLON.VertexBuffer.MatricesIndicesKind
  54873. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  54874. * - BABYLON.VertexBuffer.MatricesWeightsKind
  54875. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  54876. *
  54877. * Returns the Mesh.
  54878. */
  54879. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  54880. if (this.sourceMesh) {
  54881. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  54882. }
  54883. return this.sourceMesh;
  54884. };
  54885. /**
  54886. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  54887. * If the mesh has no geometry, it is simply returned as it is.
  54888. * The `data` are either a numeric array either a Float32Array.
  54889. * No new underlying VertexBuffer object is created.
  54890. * 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.
  54891. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  54892. *
  54893. * Possible `kind` values :
  54894. * - BABYLON.VertexBuffer.PositionKind
  54895. * - BABYLON.VertexBuffer.UVKind
  54896. * - BABYLON.VertexBuffer.UV2Kind
  54897. * - BABYLON.VertexBuffer.UV3Kind
  54898. * - BABYLON.VertexBuffer.UV4Kind
  54899. * - BABYLON.VertexBuffer.UV5Kind
  54900. * - BABYLON.VertexBuffer.UV6Kind
  54901. * - BABYLON.VertexBuffer.ColorKind
  54902. * - BABYLON.VertexBuffer.MatricesIndicesKind
  54903. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  54904. * - BABYLON.VertexBuffer.MatricesWeightsKind
  54905. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  54906. *
  54907. * Returns the Mesh.
  54908. */
  54909. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  54910. if (this.sourceMesh) {
  54911. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  54912. }
  54913. return this.sourceMesh;
  54914. };
  54915. /**
  54916. * Sets the mesh indices.
  54917. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  54918. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  54919. * This method creates a new index buffer each call.
  54920. * Returns the Mesh.
  54921. */
  54922. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  54923. if (totalVertices === void 0) { totalVertices = null; }
  54924. if (this.sourceMesh) {
  54925. this.sourceMesh.setIndices(indices, totalVertices);
  54926. }
  54927. return this.sourceMesh;
  54928. };
  54929. /**
  54930. * Boolean : True if the mesh owns the requested kind of data.
  54931. */
  54932. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  54933. return this._sourceMesh.isVerticesDataPresent(kind);
  54934. };
  54935. /**
  54936. * Returns an array of indices (IndicesArray).
  54937. */
  54938. InstancedMesh.prototype.getIndices = function () {
  54939. return this._sourceMesh.getIndices();
  54940. };
  54941. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  54942. get: function () {
  54943. return this._sourceMesh._positions;
  54944. },
  54945. enumerable: true,
  54946. configurable: true
  54947. });
  54948. /**
  54949. * Sets a new updated BoundingInfo to the mesh.
  54950. * Returns the mesh.
  54951. */
  54952. InstancedMesh.prototype.refreshBoundingInfo = function () {
  54953. var meshBB = this._sourceMesh.getBoundingInfo();
  54954. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  54955. this._updateBoundingInfo();
  54956. return this;
  54957. };
  54958. InstancedMesh.prototype._preActivate = function () {
  54959. if (this._currentLOD) {
  54960. this._currentLOD._preActivate();
  54961. }
  54962. return this;
  54963. };
  54964. InstancedMesh.prototype._activate = function (renderId) {
  54965. if (this._currentLOD) {
  54966. this._currentLOD._registerInstanceForRenderId(this, renderId);
  54967. }
  54968. return this;
  54969. };
  54970. /**
  54971. * Returns the current associated LOD AbstractMesh.
  54972. */
  54973. InstancedMesh.prototype.getLOD = function (camera) {
  54974. if (!camera) {
  54975. return this;
  54976. }
  54977. var boundingInfo = this.getBoundingInfo();
  54978. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  54979. if (this._currentLOD === this.sourceMesh) {
  54980. return this;
  54981. }
  54982. return this._currentLOD;
  54983. };
  54984. InstancedMesh.prototype._syncSubMeshes = function () {
  54985. this.releaseSubMeshes();
  54986. if (this._sourceMesh.subMeshes) {
  54987. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  54988. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  54989. }
  54990. }
  54991. return this;
  54992. };
  54993. InstancedMesh.prototype._generatePointsArray = function () {
  54994. return this._sourceMesh._generatePointsArray();
  54995. };
  54996. /**
  54997. * Creates a new InstancedMesh from the current mesh.
  54998. * - name (string) : the cloned mesh name
  54999. * - newParent (optional Node) : the optional Node to parent the clone to.
  55000. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  55001. *
  55002. * Returns the clone.
  55003. */
  55004. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  55005. var result = this._sourceMesh.createInstance(name);
  55006. // Deep copy
  55007. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  55008. // Bounding info
  55009. this.refreshBoundingInfo();
  55010. // Parent
  55011. if (newParent) {
  55012. result.parent = newParent;
  55013. }
  55014. if (!doNotCloneChildren) {
  55015. // Children
  55016. for (var index = 0; index < this.getScene().meshes.length; index++) {
  55017. var mesh = this.getScene().meshes[index];
  55018. if (mesh.parent === this) {
  55019. mesh.clone(mesh.name, result);
  55020. }
  55021. }
  55022. }
  55023. result.computeWorldMatrix(true);
  55024. return result;
  55025. };
  55026. /**
  55027. * Disposes the InstancedMesh.
  55028. * Returns nothing.
  55029. */
  55030. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  55031. // Remove from mesh
  55032. var index = this._sourceMesh.instances.indexOf(this);
  55033. this._sourceMesh.instances.splice(index, 1);
  55034. _super.prototype.dispose.call(this, doNotRecurse);
  55035. };
  55036. return InstancedMesh;
  55037. }(BABYLON.AbstractMesh));
  55038. BABYLON.InstancedMesh = InstancedMesh;
  55039. })(BABYLON || (BABYLON = {}));
  55040. //# sourceMappingURL=babylon.instancedMesh.js.map
  55041. var BABYLON;
  55042. (function (BABYLON) {
  55043. var LinesMesh = /** @class */ (function (_super) {
  55044. __extends(LinesMesh, _super);
  55045. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  55046. if (scene === void 0) { scene = null; }
  55047. if (parent === void 0) { parent = null; }
  55048. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  55049. _this.useVertexColor = useVertexColor;
  55050. _this.useVertexAlpha = useVertexAlpha;
  55051. _this.color = new BABYLON.Color3(1, 1, 1);
  55052. _this.alpha = 1;
  55053. if (source) {
  55054. _this.color = source.color.clone();
  55055. _this.alpha = source.alpha;
  55056. _this.useVertexColor = source.useVertexColor;
  55057. _this.useVertexAlpha = source.useVertexAlpha;
  55058. }
  55059. _this._intersectionThreshold = 0.1;
  55060. var defines = [];
  55061. var options = {
  55062. attributes: [BABYLON.VertexBuffer.PositionKind],
  55063. uniforms: ["world", "viewProjection"],
  55064. needAlphaBlending: true,
  55065. defines: defines
  55066. };
  55067. if (useVertexAlpha === false) {
  55068. options.needAlphaBlending = false;
  55069. }
  55070. if (!useVertexColor) {
  55071. options.uniforms.push("color");
  55072. }
  55073. else {
  55074. options.defines.push("#define VERTEXCOLOR");
  55075. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  55076. }
  55077. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  55078. return _this;
  55079. }
  55080. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  55081. /**
  55082. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  55083. * This margin is expressed in world space coordinates, so its value may vary.
  55084. * Default value is 0.1
  55085. * @returns the intersection Threshold value.
  55086. */
  55087. get: function () {
  55088. return this._intersectionThreshold;
  55089. },
  55090. /**
  55091. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  55092. * This margin is expressed in world space coordinates, so its value may vary.
  55093. * @param value the new threshold to apply
  55094. */
  55095. set: function (value) {
  55096. if (this._intersectionThreshold === value) {
  55097. return;
  55098. }
  55099. this._intersectionThreshold = value;
  55100. if (this.geometry) {
  55101. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  55102. }
  55103. },
  55104. enumerable: true,
  55105. configurable: true
  55106. });
  55107. /**
  55108. * Returns the string "LineMesh"
  55109. */
  55110. LinesMesh.prototype.getClassName = function () {
  55111. return "LinesMesh";
  55112. };
  55113. Object.defineProperty(LinesMesh.prototype, "material", {
  55114. get: function () {
  55115. return this._colorShader;
  55116. },
  55117. set: function (value) {
  55118. // Do nothing
  55119. },
  55120. enumerable: true,
  55121. configurable: true
  55122. });
  55123. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  55124. get: function () {
  55125. return false;
  55126. },
  55127. enumerable: true,
  55128. configurable: true
  55129. });
  55130. LinesMesh.prototype.createInstance = function (name) {
  55131. throw new Error("LinesMeshes do not support createInstance.");
  55132. };
  55133. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  55134. if (!this._geometry) {
  55135. return this;
  55136. }
  55137. // VBOs
  55138. this._geometry._bind(this._colorShader.getEffect());
  55139. // Color
  55140. if (!this.useVertexColor) {
  55141. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  55142. }
  55143. return this;
  55144. };
  55145. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  55146. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  55147. return this;
  55148. }
  55149. var engine = this.getScene().getEngine();
  55150. // Draw order
  55151. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  55152. return this;
  55153. };
  55154. LinesMesh.prototype.dispose = function (doNotRecurse) {
  55155. this._colorShader.dispose();
  55156. _super.prototype.dispose.call(this, doNotRecurse);
  55157. };
  55158. /**
  55159. * Returns a new LineMesh object cloned from the current one.
  55160. */
  55161. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  55162. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  55163. };
  55164. return LinesMesh;
  55165. }(BABYLON.Mesh));
  55166. BABYLON.LinesMesh = LinesMesh;
  55167. })(BABYLON || (BABYLON = {}));
  55168. //# sourceMappingURL=babylon.linesMesh.js.map
  55169. var BABYLON;
  55170. (function (BABYLON) {
  55171. var MeshBuilder = /** @class */ (function () {
  55172. function MeshBuilder() {
  55173. }
  55174. MeshBuilder.updateSideOrientation = function (orientation) {
  55175. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  55176. return BABYLON.Mesh.DOUBLESIDE;
  55177. }
  55178. if (orientation === undefined || orientation === null) {
  55179. return BABYLON.Mesh.FRONTSIDE;
  55180. }
  55181. return orientation;
  55182. };
  55183. /**
  55184. * Creates a box mesh.
  55185. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  55186. * The parameter `size` sets the size (float) of each box side (default 1).
  55187. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  55188. * 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).
  55189. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  55190. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55191. * 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).
  55192. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55193. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55194. */
  55195. MeshBuilder.CreateBox = function (name, options, scene) {
  55196. if (scene === void 0) { scene = null; }
  55197. var box = new BABYLON.Mesh(name, scene);
  55198. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55199. box._originalBuilderSideOrientation = options.sideOrientation;
  55200. var vertexData = BABYLON.VertexData.CreateBox(options);
  55201. vertexData.applyToMesh(box, options.updatable);
  55202. return box;
  55203. };
  55204. /**
  55205. * Creates a sphere mesh.
  55206. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  55207. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  55208. * 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`).
  55209. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  55210. * 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
  55211. * 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).
  55212. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55213. * 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).
  55214. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55215. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55216. */
  55217. MeshBuilder.CreateSphere = function (name, options, scene) {
  55218. var sphere = new BABYLON.Mesh(name, scene);
  55219. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55220. sphere._originalBuilderSideOrientation = options.sideOrientation;
  55221. var vertexData = BABYLON.VertexData.CreateSphere(options);
  55222. vertexData.applyToMesh(sphere, options.updatable);
  55223. return sphere;
  55224. };
  55225. /**
  55226. * Creates a plane polygonal mesh. By default, this is a disc.
  55227. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  55228. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  55229. * 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.
  55230. * 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
  55231. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55232. * 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).
  55233. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55234. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55235. */
  55236. MeshBuilder.CreateDisc = function (name, options, scene) {
  55237. if (scene === void 0) { scene = null; }
  55238. var disc = new BABYLON.Mesh(name, scene);
  55239. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55240. disc._originalBuilderSideOrientation = options.sideOrientation;
  55241. var vertexData = BABYLON.VertexData.CreateDisc(options);
  55242. vertexData.applyToMesh(disc, options.updatable);
  55243. return disc;
  55244. };
  55245. /**
  55246. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  55247. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  55248. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  55249. * 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`).
  55250. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  55251. * 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.
  55252. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55253. * 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).
  55254. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55255. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55256. */
  55257. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  55258. var sphere = new BABYLON.Mesh(name, scene);
  55259. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55260. sphere._originalBuilderSideOrientation = options.sideOrientation;
  55261. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  55262. vertexData.applyToMesh(sphere, options.updatable);
  55263. return sphere;
  55264. };
  55265. ;
  55266. /**
  55267. * Creates a ribbon mesh.
  55268. * 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.
  55269. *
  55270. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  55271. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  55272. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  55273. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  55274. * 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.
  55275. * 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.
  55276. * 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
  55277. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55278. * 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).
  55279. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55280. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55281. * 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.
  55282. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  55283. * 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
  55284. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  55285. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  55286. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55287. */
  55288. MeshBuilder.CreateRibbon = function (name, options, scene) {
  55289. if (scene === void 0) { scene = null; }
  55290. var pathArray = options.pathArray;
  55291. var closeArray = options.closeArray;
  55292. var closePath = options.closePath;
  55293. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55294. var instance = options.instance;
  55295. var updatable = options.updatable;
  55296. if (instance) {
  55297. // positionFunction : ribbon case
  55298. // only pathArray and sideOrientation parameters are taken into account for positions update
  55299. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  55300. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  55301. var positionFunction = function (positions) {
  55302. var minlg = pathArray[0].length;
  55303. var i = 0;
  55304. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  55305. for (var si = 1; si <= ns; si++) {
  55306. for (var p = 0; p < pathArray.length; p++) {
  55307. var path = pathArray[p];
  55308. var l = path.length;
  55309. minlg = (minlg < l) ? minlg : l;
  55310. var j = 0;
  55311. while (j < minlg) {
  55312. positions[i] = path[j].x;
  55313. positions[i + 1] = path[j].y;
  55314. positions[i + 2] = path[j].z;
  55315. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  55316. BABYLON.Tmp.Vector3[0].x = path[j].x;
  55317. }
  55318. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  55319. BABYLON.Tmp.Vector3[1].x = path[j].x;
  55320. }
  55321. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  55322. BABYLON.Tmp.Vector3[0].y = path[j].y;
  55323. }
  55324. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  55325. BABYLON.Tmp.Vector3[1].y = path[j].y;
  55326. }
  55327. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  55328. BABYLON.Tmp.Vector3[0].z = path[j].z;
  55329. }
  55330. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  55331. BABYLON.Tmp.Vector3[1].z = path[j].z;
  55332. }
  55333. j++;
  55334. i += 3;
  55335. }
  55336. if (instance._closePath) {
  55337. positions[i] = path[0].x;
  55338. positions[i + 1] = path[0].y;
  55339. positions[i + 2] = path[0].z;
  55340. i += 3;
  55341. }
  55342. }
  55343. }
  55344. };
  55345. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55346. positionFunction(positions);
  55347. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  55348. instance._boundingInfo.update(instance._worldMatrix);
  55349. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  55350. if (options.colors) {
  55351. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55352. for (var c = 0; c < options.colors.length; c++) {
  55353. colors[c * 4] = options.colors[c].r;
  55354. colors[c * 4 + 1] = options.colors[c].g;
  55355. colors[c * 4 + 2] = options.colors[c].b;
  55356. colors[c * 4 + 3] = options.colors[c].a;
  55357. }
  55358. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  55359. }
  55360. if (options.uvs) {
  55361. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55362. for (var i = 0; i < options.uvs.length; i++) {
  55363. uvs[i * 2] = options.uvs[i].x;
  55364. uvs[i * 2 + 1] = options.uvs[i].y;
  55365. }
  55366. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  55367. }
  55368. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  55369. var indices = instance.getIndices();
  55370. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55371. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  55372. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  55373. if (instance._closePath) {
  55374. var indexFirst = 0;
  55375. var indexLast = 0;
  55376. for (var p = 0; p < pathArray.length; p++) {
  55377. indexFirst = instance._idx[p] * 3;
  55378. if (p + 1 < pathArray.length) {
  55379. indexLast = (instance._idx[p + 1] - 1) * 3;
  55380. }
  55381. else {
  55382. indexLast = normals.length - 3;
  55383. }
  55384. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  55385. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  55386. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  55387. normals[indexLast] = normals[indexFirst];
  55388. normals[indexLast + 1] = normals[indexFirst + 1];
  55389. normals[indexLast + 2] = normals[indexFirst + 2];
  55390. }
  55391. }
  55392. if (!(instance.areNormalsFrozen)) {
  55393. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  55394. }
  55395. }
  55396. return instance;
  55397. }
  55398. else {
  55399. var ribbon = new BABYLON.Mesh(name, scene);
  55400. ribbon._originalBuilderSideOrientation = sideOrientation;
  55401. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  55402. if (closePath) {
  55403. ribbon._idx = vertexData._idx;
  55404. }
  55405. ribbon._closePath = closePath;
  55406. ribbon._closeArray = closeArray;
  55407. vertexData.applyToMesh(ribbon, updatable);
  55408. return ribbon;
  55409. }
  55410. };
  55411. /**
  55412. * Creates a cylinder or a cone mesh.
  55413. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  55414. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  55415. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  55416. * 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.
  55417. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  55418. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  55419. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  55420. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  55421. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  55422. * 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).
  55423. * 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
  55424. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  55425. * 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
  55426. * 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.
  55427. * If `enclose` is false, a ring surface is one element.
  55428. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  55429. * 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
  55430. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55431. * 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).
  55432. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55433. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55434. */
  55435. MeshBuilder.CreateCylinder = function (name, options, scene) {
  55436. var cylinder = new BABYLON.Mesh(name, scene);
  55437. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55438. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  55439. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  55440. vertexData.applyToMesh(cylinder, options.updatable);
  55441. return cylinder;
  55442. };
  55443. /**
  55444. * Creates a torus mesh.
  55445. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  55446. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  55447. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  55448. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  55449. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55450. * 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).
  55451. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55452. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55453. */
  55454. MeshBuilder.CreateTorus = function (name, options, scene) {
  55455. var torus = new BABYLON.Mesh(name, scene);
  55456. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55457. torus._originalBuilderSideOrientation = options.sideOrientation;
  55458. var vertexData = BABYLON.VertexData.CreateTorus(options);
  55459. vertexData.applyToMesh(torus, options.updatable);
  55460. return torus;
  55461. };
  55462. /**
  55463. * Creates a torus knot mesh.
  55464. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  55465. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  55466. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  55467. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  55468. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  55469. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55470. * 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).
  55471. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55472. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55473. */
  55474. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  55475. var torusKnot = new BABYLON.Mesh(name, scene);
  55476. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55477. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  55478. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  55479. vertexData.applyToMesh(torusKnot, options.updatable);
  55480. return torusKnot;
  55481. };
  55482. /**
  55483. * Creates a line system mesh.
  55484. * A line system is a pool of many lines gathered in a single mesh.
  55485. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  55486. * 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.
  55487. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  55488. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  55489. * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter. The way to update it is the same than for
  55490. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  55491. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  55492. * 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
  55493. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  55494. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55495. */
  55496. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  55497. var instance = options.instance;
  55498. var lines = options.lines;
  55499. var colors = options.colors;
  55500. if (instance) {
  55501. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55502. var vertexColor;
  55503. var lineColors;
  55504. if (colors) {
  55505. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55506. }
  55507. var i = 0;
  55508. var c = 0;
  55509. for (var l = 0; l < lines.length; l++) {
  55510. var points = lines[l];
  55511. for (var p = 0; p < points.length; p++) {
  55512. positions[i] = points[p].x;
  55513. positions[i + 1] = points[p].y;
  55514. positions[i + 2] = points[p].z;
  55515. if (colors && vertexColor) {
  55516. lineColors = colors[l];
  55517. vertexColor[c] = lineColors[p].r;
  55518. vertexColor[c + 1] = lineColors[p].g;
  55519. vertexColor[c + 2] = lineColors[p].b;
  55520. vertexColor[c + 3] = lineColors[p].a;
  55521. c += 4;
  55522. }
  55523. i += 3;
  55524. }
  55525. }
  55526. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  55527. if (colors && vertexColor) {
  55528. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  55529. }
  55530. return instance;
  55531. }
  55532. // line system creation
  55533. var useVertexColor = (colors) ? true : false;
  55534. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  55535. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  55536. vertexData.applyToMesh(lineSystem, options.updatable);
  55537. return lineSystem;
  55538. };
  55539. /**
  55540. * Creates a line mesh.
  55541. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  55542. * 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.
  55543. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55544. * The parameter `points` is an array successive Vector3.
  55545. * 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
  55546. * The optional parameter `colors` is an array of successive Color4, one per line point.
  55547. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  55548. * When updating an instance, remember that only point positions can change, not the number of points.
  55549. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55550. */
  55551. MeshBuilder.CreateLines = function (name, options, scene) {
  55552. if (scene === void 0) { scene = null; }
  55553. var colors = (options.colors) ? [options.colors] : null;
  55554. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  55555. return lines;
  55556. };
  55557. /**
  55558. * Creates a dashed line mesh.
  55559. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  55560. * 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.
  55561. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55562. * The parameter `points` is an array successive Vector3.
  55563. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  55564. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  55565. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  55566. * 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
  55567. * When updating an instance, remember that only point positions can change, not the number of points.
  55568. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55569. */
  55570. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  55571. if (scene === void 0) { scene = null; }
  55572. var points = options.points;
  55573. var instance = options.instance;
  55574. var gapSize = options.gapSize || 1;
  55575. var dashSize = options.dashSize || 3;
  55576. if (instance) {
  55577. var positionFunction = function (positions) {
  55578. var curvect = BABYLON.Vector3.Zero();
  55579. var nbSeg = positions.length / 6;
  55580. var lg = 0;
  55581. var nb = 0;
  55582. var shft = 0;
  55583. var dashshft = 0;
  55584. var curshft = 0;
  55585. var p = 0;
  55586. var i = 0;
  55587. var j = 0;
  55588. for (i = 0; i < points.length - 1; i++) {
  55589. points[i + 1].subtractToRef(points[i], curvect);
  55590. lg += curvect.length();
  55591. }
  55592. shft = lg / nbSeg;
  55593. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  55594. for (i = 0; i < points.length - 1; i++) {
  55595. points[i + 1].subtractToRef(points[i], curvect);
  55596. nb = Math.floor(curvect.length() / shft);
  55597. curvect.normalize();
  55598. j = 0;
  55599. while (j < nb && p < positions.length) {
  55600. curshft = shft * j;
  55601. positions[p] = points[i].x + curshft * curvect.x;
  55602. positions[p + 1] = points[i].y + curshft * curvect.y;
  55603. positions[p + 2] = points[i].z + curshft * curvect.z;
  55604. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  55605. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  55606. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  55607. p += 6;
  55608. j++;
  55609. }
  55610. }
  55611. while (p < positions.length) {
  55612. positions[p] = points[i].x;
  55613. positions[p + 1] = points[i].y;
  55614. positions[p + 2] = points[i].z;
  55615. p += 3;
  55616. }
  55617. };
  55618. instance.updateMeshPositions(positionFunction, false);
  55619. return instance;
  55620. }
  55621. // dashed lines creation
  55622. var dashedLines = new BABYLON.LinesMesh(name, scene);
  55623. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  55624. vertexData.applyToMesh(dashedLines, options.updatable);
  55625. dashedLines.dashSize = dashSize;
  55626. dashedLines.gapSize = gapSize;
  55627. return dashedLines;
  55628. };
  55629. /**
  55630. * Creates an extruded shape mesh.
  55631. * 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.
  55632. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  55633. *
  55634. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  55635. * 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
  55636. * extruded along the Z axis.
  55637. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  55638. * 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.
  55639. * The parameter `scale` (float, default 1) is the value to scale the shape.
  55640. * 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
  55641. * 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
  55642. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  55643. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55644. * 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).
  55645. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55646. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55647. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55648. */
  55649. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  55650. if (scene === void 0) { scene = null; }
  55651. var path = options.path;
  55652. var shape = options.shape;
  55653. var scale = options.scale || 1;
  55654. var rotation = options.rotation || 0;
  55655. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  55656. var updatable = options.updatable;
  55657. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55658. var instance = options.instance || null;
  55659. var invertUV = options.invertUV || false;
  55660. 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);
  55661. };
  55662. /**
  55663. * Creates an custom extruded shape mesh.
  55664. * 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.
  55665. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  55666. *
  55667. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  55668. * 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
  55669. * extruded along the Z axis.
  55670. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  55671. * 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
  55672. * and the distance of this point from the begining of the path :
  55673. * ```javascript
  55674. * var rotationFunction = function(i, distance) {
  55675. * // do things
  55676. * return rotationValue; }
  55677. * ```
  55678. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  55679. * 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
  55680. * and the distance of this point from the begining of the path :
  55681. * ```javascript
  55682. * var scaleFunction = function(i, distance) {
  55683. * // do things
  55684. * return scaleValue;}
  55685. * ```
  55686. * It must returns a float value that will be the scale value applied to the shape on each path point.
  55687. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  55688. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  55689. * 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
  55690. * 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
  55691. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  55692. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55693. * 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).
  55694. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55695. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55696. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55697. */
  55698. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  55699. var path = options.path;
  55700. var shape = options.shape;
  55701. var scaleFunction = options.scaleFunction || (function () { return 1; });
  55702. var rotationFunction = options.rotationFunction || (function () { return 0; });
  55703. var ribbonCloseArray = options.ribbonCloseArray || false;
  55704. var ribbonClosePath = options.ribbonClosePath || false;
  55705. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  55706. var updatable = options.updatable;
  55707. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55708. var instance = options.instance;
  55709. var invertUV = options.invertUV || false;
  55710. 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);
  55711. };
  55712. /**
  55713. * Creates lathe mesh.
  55714. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  55715. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  55716. *
  55717. * 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
  55718. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  55719. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  55720. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  55721. * 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.
  55722. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  55723. * 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
  55724. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55725. * 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).
  55726. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55727. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55728. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55729. */
  55730. MeshBuilder.CreateLathe = function (name, options, scene) {
  55731. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  55732. var closed = (options.closed === undefined) ? true : options.closed;
  55733. var shape = options.shape;
  55734. var radius = options.radius || 1;
  55735. var tessellation = options.tessellation || 64;
  55736. var updatable = options.updatable;
  55737. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55738. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  55739. var pi2 = Math.PI * 2;
  55740. var paths = new Array();
  55741. var invertUV = options.invertUV || false;
  55742. var i = 0;
  55743. var p = 0;
  55744. var step = pi2 / tessellation * arc;
  55745. var rotated;
  55746. var path = new Array();
  55747. ;
  55748. for (i = 0; i <= tessellation; i++) {
  55749. var path = [];
  55750. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  55751. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  55752. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  55753. }
  55754. for (p = 0; p < shape.length; p++) {
  55755. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  55756. path.push(rotated);
  55757. }
  55758. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  55759. 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));
  55760. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  55761. }
  55762. paths.push(path);
  55763. }
  55764. // lathe ribbon
  55765. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  55766. return lathe;
  55767. };
  55768. /**
  55769. * Creates a plane mesh.
  55770. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  55771. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  55772. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  55773. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  55774. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55775. * 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).
  55776. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55777. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55778. */
  55779. MeshBuilder.CreatePlane = function (name, options, scene) {
  55780. var plane = new BABYLON.Mesh(name, scene);
  55781. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55782. plane._originalBuilderSideOrientation = options.sideOrientation;
  55783. var vertexData = BABYLON.VertexData.CreatePlane(options);
  55784. vertexData.applyToMesh(plane, options.updatable);
  55785. if (options.sourcePlane) {
  55786. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  55787. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  55788. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  55789. plane.rotate(vectorProduct, product);
  55790. }
  55791. return plane;
  55792. };
  55793. /**
  55794. * Creates a ground mesh.
  55795. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  55796. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  55797. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  55798. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55799. */
  55800. MeshBuilder.CreateGround = function (name, options, scene) {
  55801. var ground = new BABYLON.GroundMesh(name, scene);
  55802. ground._setReady(false);
  55803. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  55804. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  55805. ground._width = options.width || 1;
  55806. ground._height = options.height || 1;
  55807. ground._maxX = ground._width / 2;
  55808. ground._maxZ = ground._height / 2;
  55809. ground._minX = -ground._maxX;
  55810. ground._minZ = -ground._maxZ;
  55811. var vertexData = BABYLON.VertexData.CreateGround(options);
  55812. vertexData.applyToMesh(ground, options.updatable);
  55813. ground._setReady(true);
  55814. return ground;
  55815. };
  55816. /**
  55817. * Creates a tiled ground mesh.
  55818. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  55819. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  55820. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  55821. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  55822. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  55823. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  55824. * numbers of subdivisions on the ground width and height of each tile.
  55825. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55826. */
  55827. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  55828. var tiledGround = new BABYLON.Mesh(name, scene);
  55829. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  55830. vertexData.applyToMesh(tiledGround, options.updatable);
  55831. return tiledGround;
  55832. };
  55833. /**
  55834. * Creates a ground mesh from a height map.
  55835. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  55836. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  55837. * The parameter `url` sets the URL of the height map image resource.
  55838. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  55839. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  55840. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  55841. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  55842. * 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.
  55843. * 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).
  55844. * This function is passed the newly built mesh :
  55845. * ```javascript
  55846. * function(mesh) { // do things
  55847. * return; }
  55848. * ```
  55849. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55850. */
  55851. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  55852. var width = options.width || 10.0;
  55853. var height = options.height || 10.0;
  55854. var subdivisions = options.subdivisions || 1 | 0;
  55855. var minHeight = options.minHeight || 0.0;
  55856. var maxHeight = options.maxHeight || 1.0;
  55857. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  55858. var updatable = options.updatable;
  55859. var onReady = options.onReady;
  55860. var ground = new BABYLON.GroundMesh(name, scene);
  55861. ground._subdivisionsX = subdivisions;
  55862. ground._subdivisionsY = subdivisions;
  55863. ground._width = width;
  55864. ground._height = height;
  55865. ground._maxX = ground._width / 2.0;
  55866. ground._maxZ = ground._height / 2.0;
  55867. ground._minX = -ground._maxX;
  55868. ground._minZ = -ground._maxZ;
  55869. ground._setReady(false);
  55870. var onload = function (img) {
  55871. // Getting height map data
  55872. var canvas = document.createElement("canvas");
  55873. var context = canvas.getContext("2d");
  55874. if (!context) {
  55875. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  55876. }
  55877. if (scene.isDisposed) {
  55878. return;
  55879. }
  55880. var bufferWidth = img.width;
  55881. var bufferHeight = img.height;
  55882. canvas.width = bufferWidth;
  55883. canvas.height = bufferHeight;
  55884. context.drawImage(img, 0, 0);
  55885. // Create VertexData from map data
  55886. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  55887. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  55888. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  55889. width: width, height: height,
  55890. subdivisions: subdivisions,
  55891. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  55892. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  55893. });
  55894. vertexData.applyToMesh(ground, updatable);
  55895. ground._setReady(true);
  55896. //execute ready callback, if set
  55897. if (onReady) {
  55898. onReady(ground);
  55899. }
  55900. };
  55901. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  55902. return ground;
  55903. };
  55904. /**
  55905. * Creates a polygon mesh.
  55906. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  55907. * 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.
  55908. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55909. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55910. * 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).
  55911. * Remember you can only change the shape positions, not their number when updating a polygon.
  55912. */
  55913. MeshBuilder.CreatePolygon = function (name, options, scene) {
  55914. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55915. var shape = options.shape;
  55916. var holes = options.holes || [];
  55917. var depth = options.depth || 0;
  55918. var contours = [];
  55919. var hole = [];
  55920. for (var i = 0; i < shape.length; i++) {
  55921. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  55922. }
  55923. var epsilon = 0.00000001;
  55924. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  55925. contours.pop();
  55926. }
  55927. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  55928. for (var hNb = 0; hNb < holes.length; hNb++) {
  55929. hole = [];
  55930. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  55931. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  55932. }
  55933. polygonTriangulation.addHole(hole);
  55934. }
  55935. var polygon = polygonTriangulation.build(options.updatable, depth);
  55936. polygon._originalBuilderSideOrientation = options.sideOrientation;
  55937. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  55938. vertexData.applyToMesh(polygon, options.updatable);
  55939. return polygon;
  55940. };
  55941. ;
  55942. /**
  55943. * Creates an extruded polygon mesh, with depth in the Y direction.
  55944. * 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).
  55945. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  55946. */
  55947. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  55948. return MeshBuilder.CreatePolygon(name, options, scene);
  55949. };
  55950. ;
  55951. /**
  55952. * Creates a tube mesh.
  55953. * 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.
  55954. *
  55955. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  55956. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  55957. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  55958. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  55959. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  55960. * 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.
  55961. * It must return a radius value (positive float) :
  55962. * ```javascript
  55963. * var radiusFunction = function(i, distance) {
  55964. * // do things
  55965. * return radius; }
  55966. * ```
  55967. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  55968. * 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
  55969. * 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
  55970. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55971. * 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).
  55972. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55973. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55974. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55975. */
  55976. MeshBuilder.CreateTube = function (name, options, scene) {
  55977. var path = options.path;
  55978. var instance = options.instance;
  55979. var radius = 1.0;
  55980. if (instance) {
  55981. radius = instance.radius;
  55982. }
  55983. if (options.radius !== undefined) {
  55984. radius = options.radius;
  55985. }
  55986. ;
  55987. var tessellation = options.tessellation || 64 | 0;
  55988. var radiusFunction = options.radiusFunction || null;
  55989. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  55990. var invertUV = options.invertUV || false;
  55991. var updatable = options.updatable;
  55992. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55993. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  55994. // tube geometry
  55995. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  55996. var tangents = path3D.getTangents();
  55997. var normals = path3D.getNormals();
  55998. var distances = path3D.getDistances();
  55999. var pi2 = Math.PI * 2;
  56000. var step = pi2 / tessellation * arc;
  56001. var returnRadius = function () { return radius; };
  56002. var radiusFunctionFinal = radiusFunction || returnRadius;
  56003. var circlePath;
  56004. var rad;
  56005. var normal;
  56006. var rotated;
  56007. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  56008. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  56009. for (var i = 0; i < path.length; i++) {
  56010. rad = radiusFunctionFinal(i, distances[i]); // current radius
  56011. circlePath = Array(); // current circle array
  56012. normal = normals[i]; // current normal
  56013. for (var t = 0; t < tessellation; t++) {
  56014. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  56015. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  56016. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  56017. rotated.scaleInPlace(rad).addInPlace(path[i]);
  56018. circlePath[t] = rotated;
  56019. }
  56020. circlePaths[index] = circlePath;
  56021. index++;
  56022. }
  56023. // cap
  56024. var capPath = function (nbPoints, pathIndex) {
  56025. var pointCap = Array();
  56026. for (var i = 0; i < nbPoints; i++) {
  56027. pointCap.push(path[pathIndex]);
  56028. }
  56029. return pointCap;
  56030. };
  56031. switch (cap) {
  56032. case BABYLON.Mesh.NO_CAP:
  56033. break;
  56034. case BABYLON.Mesh.CAP_START:
  56035. circlePaths[0] = capPath(tessellation, 0);
  56036. circlePaths[1] = circlePaths[2].slice(0);
  56037. break;
  56038. case BABYLON.Mesh.CAP_END:
  56039. circlePaths[index] = circlePaths[index - 1].slice(0);
  56040. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  56041. break;
  56042. case BABYLON.Mesh.CAP_ALL:
  56043. circlePaths[0] = capPath(tessellation, 0);
  56044. circlePaths[1] = circlePaths[2].slice(0);
  56045. circlePaths[index] = circlePaths[index - 1].slice(0);
  56046. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  56047. break;
  56048. default:
  56049. break;
  56050. }
  56051. return circlePaths;
  56052. };
  56053. var path3D;
  56054. var pathArray;
  56055. if (instance) {
  56056. var arc = options.arc || instance.arc;
  56057. path3D = (instance.path3D).update(path);
  56058. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  56059. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  56060. instance.path3D = path3D;
  56061. instance.pathArray = pathArray;
  56062. instance.arc = arc;
  56063. instance.radius = radius;
  56064. return instance;
  56065. }
  56066. // tube creation
  56067. path3D = new BABYLON.Path3D(path);
  56068. var newPathArray = new Array();
  56069. cap = (cap < 0 || cap > 3) ? 0 : cap;
  56070. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  56071. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  56072. tube.pathArray = pathArray;
  56073. tube.path3D = path3D;
  56074. tube.tessellation = tessellation;
  56075. tube.cap = cap;
  56076. tube.arc = options.arc;
  56077. tube.radius = radius;
  56078. return tube;
  56079. };
  56080. /**
  56081. * Creates a polyhedron mesh.
  56082. *
  56083. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  56084. * 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
  56085. * to choose the wanted type.
  56086. * The parameter `size` (positive float, default 1) sets the polygon size.
  56087. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  56088. * 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`.
  56089. * 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
  56090. * 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)`).
  56091. * 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
  56092. * 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.
  56093. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56094. * 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).
  56095. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56096. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56097. */
  56098. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  56099. var polyhedron = new BABYLON.Mesh(name, scene);
  56100. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56101. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  56102. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  56103. vertexData.applyToMesh(polyhedron, options.updatable);
  56104. return polyhedron;
  56105. };
  56106. /**
  56107. * Creates a decal mesh.
  56108. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  56109. * 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.
  56110. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  56111. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  56112. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  56113. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  56114. */
  56115. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  56116. var indices = sourceMesh.getIndices();
  56117. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56118. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56119. var position = options.position || BABYLON.Vector3.Zero();
  56120. var normal = options.normal || BABYLON.Vector3.Up();
  56121. var size = options.size || BABYLON.Vector3.One();
  56122. var angle = options.angle || 0;
  56123. // Getting correct rotation
  56124. if (!normal) {
  56125. var target = new BABYLON.Vector3(0, 0, 1);
  56126. var camera = sourceMesh.getScene().activeCamera;
  56127. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  56128. normal = camera.globalPosition.subtract(cameraWorldTarget);
  56129. }
  56130. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  56131. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  56132. var pitch = Math.atan2(normal.y, len);
  56133. // Matrix
  56134. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  56135. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  56136. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  56137. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  56138. var vertexData = new BABYLON.VertexData();
  56139. vertexData.indices = [];
  56140. vertexData.positions = [];
  56141. vertexData.normals = [];
  56142. vertexData.uvs = [];
  56143. var currentVertexDataIndex = 0;
  56144. var extractDecalVector3 = function (indexId) {
  56145. var result = new BABYLON.PositionNormalVertex();
  56146. if (!indices || !positions || !normals) {
  56147. return result;
  56148. }
  56149. var vertexId = indices[indexId];
  56150. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  56151. // Send vector to decal local world
  56152. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  56153. // Get normal
  56154. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  56155. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  56156. return result;
  56157. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  56158. var clip = function (vertices, axis) {
  56159. if (vertices.length === 0) {
  56160. return vertices;
  56161. }
  56162. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  56163. var clipVertices = function (v0, v1) {
  56164. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  56165. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  56166. };
  56167. var result = new Array();
  56168. for (var index = 0; index < vertices.length; index += 3) {
  56169. var v1Out;
  56170. var v2Out;
  56171. var v3Out;
  56172. var total = 0;
  56173. var nV1 = null;
  56174. var nV2 = null;
  56175. var nV3 = null;
  56176. var nV4 = null;
  56177. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  56178. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  56179. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  56180. v1Out = d1 > 0;
  56181. v2Out = d2 > 0;
  56182. v3Out = d3 > 0;
  56183. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  56184. switch (total) {
  56185. case 0:
  56186. result.push(vertices[index]);
  56187. result.push(vertices[index + 1]);
  56188. result.push(vertices[index + 2]);
  56189. break;
  56190. case 1:
  56191. if (v1Out) {
  56192. nV1 = vertices[index + 1];
  56193. nV2 = vertices[index + 2];
  56194. nV3 = clipVertices(vertices[index], nV1);
  56195. nV4 = clipVertices(vertices[index], nV2);
  56196. }
  56197. if (v2Out) {
  56198. nV1 = vertices[index];
  56199. nV2 = vertices[index + 2];
  56200. nV3 = clipVertices(vertices[index + 1], nV1);
  56201. nV4 = clipVertices(vertices[index + 1], nV2);
  56202. result.push(nV3);
  56203. result.push(nV2.clone());
  56204. result.push(nV1.clone());
  56205. result.push(nV2.clone());
  56206. result.push(nV3.clone());
  56207. result.push(nV4);
  56208. break;
  56209. }
  56210. if (v3Out) {
  56211. nV1 = vertices[index];
  56212. nV2 = vertices[index + 1];
  56213. nV3 = clipVertices(vertices[index + 2], nV1);
  56214. nV4 = clipVertices(vertices[index + 2], nV2);
  56215. }
  56216. if (nV1 && nV2 && nV3 && nV4) {
  56217. result.push(nV1.clone());
  56218. result.push(nV2.clone());
  56219. result.push(nV3);
  56220. result.push(nV4);
  56221. result.push(nV3.clone());
  56222. result.push(nV2.clone());
  56223. }
  56224. break;
  56225. case 2:
  56226. if (!v1Out) {
  56227. nV1 = vertices[index].clone();
  56228. nV2 = clipVertices(nV1, vertices[index + 1]);
  56229. nV3 = clipVertices(nV1, vertices[index + 2]);
  56230. result.push(nV1);
  56231. result.push(nV2);
  56232. result.push(nV3);
  56233. }
  56234. if (!v2Out) {
  56235. nV1 = vertices[index + 1].clone();
  56236. nV2 = clipVertices(nV1, vertices[index + 2]);
  56237. nV3 = clipVertices(nV1, vertices[index]);
  56238. result.push(nV1);
  56239. result.push(nV2);
  56240. result.push(nV3);
  56241. }
  56242. if (!v3Out) {
  56243. nV1 = vertices[index + 2].clone();
  56244. nV2 = clipVertices(nV1, vertices[index]);
  56245. nV3 = clipVertices(nV1, vertices[index + 1]);
  56246. result.push(nV1);
  56247. result.push(nV2);
  56248. result.push(nV3);
  56249. }
  56250. break;
  56251. case 3:
  56252. break;
  56253. }
  56254. }
  56255. return result;
  56256. };
  56257. for (var index = 0; index < indices.length; index += 3) {
  56258. var faceVertices = new Array();
  56259. faceVertices.push(extractDecalVector3(index));
  56260. faceVertices.push(extractDecalVector3(index + 1));
  56261. faceVertices.push(extractDecalVector3(index + 2));
  56262. // Clip
  56263. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  56264. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  56265. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  56266. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  56267. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  56268. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  56269. if (faceVertices.length === 0) {
  56270. continue;
  56271. }
  56272. // Add UVs and get back to world
  56273. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  56274. var vertex = faceVertices[vIndex];
  56275. //TODO check for Int32Array | Uint32Array | Uint16Array
  56276. vertexData.indices.push(currentVertexDataIndex);
  56277. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  56278. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  56279. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  56280. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  56281. currentVertexDataIndex++;
  56282. }
  56283. }
  56284. // Return mesh
  56285. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  56286. vertexData.applyToMesh(decal);
  56287. decal.position = position.clone();
  56288. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  56289. return decal;
  56290. };
  56291. // Privates
  56292. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  56293. // extrusion geometry
  56294. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  56295. var tangents = path3D.getTangents();
  56296. var normals = path3D.getNormals();
  56297. var binormals = path3D.getBinormals();
  56298. var distances = path3D.getDistances();
  56299. var angle = 0;
  56300. var returnScale = function () { return scale !== null ? scale : 1; };
  56301. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  56302. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  56303. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  56304. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  56305. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  56306. for (var i = 0; i < curve.length; i++) {
  56307. var shapePath = new Array();
  56308. var angleStep = rotate(i, distances[i]);
  56309. var scaleRatio = scl(i, distances[i]);
  56310. for (var p = 0; p < shape.length; p++) {
  56311. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  56312. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  56313. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  56314. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  56315. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  56316. shapePath[p] = rotated;
  56317. }
  56318. shapePaths[index] = shapePath;
  56319. angle += angleStep;
  56320. index++;
  56321. }
  56322. // cap
  56323. var capPath = function (shapePath) {
  56324. var pointCap = Array();
  56325. var barycenter = BABYLON.Vector3.Zero();
  56326. var i;
  56327. for (i = 0; i < shapePath.length; i++) {
  56328. barycenter.addInPlace(shapePath[i]);
  56329. }
  56330. barycenter.scaleInPlace(1.0 / shapePath.length);
  56331. for (i = 0; i < shapePath.length; i++) {
  56332. pointCap.push(barycenter);
  56333. }
  56334. return pointCap;
  56335. };
  56336. switch (cap) {
  56337. case BABYLON.Mesh.NO_CAP:
  56338. break;
  56339. case BABYLON.Mesh.CAP_START:
  56340. shapePaths[0] = capPath(shapePaths[2]);
  56341. shapePaths[1] = shapePaths[2];
  56342. break;
  56343. case BABYLON.Mesh.CAP_END:
  56344. shapePaths[index] = shapePaths[index - 1];
  56345. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  56346. break;
  56347. case BABYLON.Mesh.CAP_ALL:
  56348. shapePaths[0] = capPath(shapePaths[2]);
  56349. shapePaths[1] = shapePaths[2];
  56350. shapePaths[index] = shapePaths[index - 1];
  56351. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  56352. break;
  56353. default:
  56354. break;
  56355. }
  56356. return shapePaths;
  56357. };
  56358. var path3D;
  56359. var pathArray;
  56360. if (instance) {
  56361. path3D = (instance.path3D).update(curve);
  56362. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  56363. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  56364. return instance;
  56365. }
  56366. // extruded shape creation
  56367. path3D = new BABYLON.Path3D(curve);
  56368. var newShapePaths = new Array();
  56369. cap = (cap < 0 || cap > 3) ? 0 : cap;
  56370. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  56371. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  56372. extrudedGeneric.pathArray = pathArray;
  56373. extrudedGeneric.path3D = path3D;
  56374. extrudedGeneric.cap = cap;
  56375. return extrudedGeneric;
  56376. };
  56377. return MeshBuilder;
  56378. }());
  56379. BABYLON.MeshBuilder = MeshBuilder;
  56380. })(BABYLON || (BABYLON = {}));
  56381. //# sourceMappingURL=babylon.meshBuilder.js.map
  56382. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  56383. var BABYLON;
  56384. (function (BABYLON) {
  56385. /**
  56386. * Draco compression (https://google.github.io/draco/)
  56387. */
  56388. var DracoCompression = /** @class */ (function () {
  56389. /**
  56390. * Constructor
  56391. * @param numWorkers The number of workers for async operations
  56392. */
  56393. function DracoCompression(numWorkers) {
  56394. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  56395. var workers = new Array(numWorkers);
  56396. for (var i = 0; i < workers.length; i++) {
  56397. var worker = new Worker(DracoCompression._WorkerBlobUrl);
  56398. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  56399. workers[i] = worker;
  56400. }
  56401. this._workerPool = new BABYLON.WorkerPool(workers);
  56402. }
  56403. /**
  56404. * Stop all async operations and release resources.
  56405. */
  56406. DracoCompression.prototype.dispose = function () {
  56407. this._workerPool.dispose();
  56408. delete this._workerPool;
  56409. };
  56410. /**
  56411. * Decode Draco compressed mesh data to vertex data.
  56412. * @param data The array buffer view for the Draco compression data
  56413. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  56414. * @returns A promise that resolves with the decoded vertex data
  56415. */
  56416. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  56417. var _this = this;
  56418. return new Promise(function (resolve, reject) {
  56419. _this._workerPool.push(function (worker, onComplete) {
  56420. var vertexData = new BABYLON.VertexData();
  56421. var onError = function (error) {
  56422. worker.removeEventListener("error", onError);
  56423. worker.removeEventListener("message", onMessage);
  56424. reject(error);
  56425. onComplete();
  56426. };
  56427. var onMessage = function (message) {
  56428. if (message.data === "done") {
  56429. worker.removeEventListener("error", onError);
  56430. worker.removeEventListener("message", onMessage);
  56431. resolve(vertexData);
  56432. onComplete();
  56433. }
  56434. else if (message.data.id === "indices") {
  56435. vertexData.indices = message.data.value;
  56436. }
  56437. else {
  56438. vertexData.set(message.data.value, message.data.id);
  56439. }
  56440. };
  56441. worker.addEventListener("error", onError);
  56442. worker.addEventListener("message", onMessage);
  56443. var dataCopy = new Uint8Array(data.byteLength);
  56444. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  56445. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  56446. });
  56447. });
  56448. };
  56449. /**
  56450. * The worker function that gets converted to a blob url to pass into a worker.
  56451. */
  56452. DracoCompression._Worker = function () {
  56453. // self is actually a DedicatedWorkerGlobalScope
  56454. var _self = self;
  56455. var decodeMesh = function (data, attributes) {
  56456. var dracoModule = new DracoDecoderModule();
  56457. var buffer = new dracoModule.DecoderBuffer();
  56458. buffer.Init(data, data.byteLength);
  56459. var decoder = new dracoModule.Decoder();
  56460. var geometry;
  56461. var status;
  56462. try {
  56463. var type = decoder.GetEncodedGeometryType(buffer);
  56464. switch (type) {
  56465. case dracoModule.TRIANGULAR_MESH:
  56466. geometry = new dracoModule.Mesh();
  56467. status = decoder.DecodeBufferToMesh(buffer, geometry);
  56468. break;
  56469. case dracoModule.POINT_CLOUD:
  56470. geometry = new dracoModule.PointCloud();
  56471. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  56472. break;
  56473. default:
  56474. throw new Error("Invalid geometry type " + type);
  56475. }
  56476. if (!status.ok() || !geometry.ptr) {
  56477. throw new Error(status.error_msg());
  56478. }
  56479. var numPoints = geometry.num_points();
  56480. if (type === dracoModule.TRIANGULAR_MESH) {
  56481. var numFaces = geometry.num_faces();
  56482. var faceIndices = new dracoModule.DracoInt32Array();
  56483. try {
  56484. var indices = new Uint32Array(numFaces * 3);
  56485. for (var i = 0; i < numFaces; i++) {
  56486. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  56487. var offset = i * 3;
  56488. indices[offset + 0] = faceIndices.GetValue(0);
  56489. indices[offset + 1] = faceIndices.GetValue(1);
  56490. indices[offset + 2] = faceIndices.GetValue(2);
  56491. }
  56492. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  56493. }
  56494. finally {
  56495. dracoModule.destroy(faceIndices);
  56496. }
  56497. }
  56498. for (var kind in attributes) {
  56499. var uniqueId = attributes[kind];
  56500. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  56501. var dracoData = new dracoModule.DracoFloat32Array();
  56502. try {
  56503. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  56504. var babylonData = new Float32Array(numPoints * attribute.num_components());
  56505. for (var i = 0; i < babylonData.length; i++) {
  56506. babylonData[i] = dracoData.GetValue(i);
  56507. }
  56508. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  56509. }
  56510. finally {
  56511. dracoModule.destroy(dracoData);
  56512. }
  56513. }
  56514. }
  56515. finally {
  56516. if (geometry) {
  56517. dracoModule.destroy(geometry);
  56518. }
  56519. dracoModule.destroy(decoder);
  56520. dracoModule.destroy(buffer);
  56521. }
  56522. _self.postMessage("done");
  56523. };
  56524. _self.onmessage = function (event) {
  56525. switch (event.data.id) {
  56526. case "initDecoder": {
  56527. importScripts(event.data.url);
  56528. break;
  56529. }
  56530. case "decodeMesh": {
  56531. decodeMesh(event.data.data, event.data.attributes);
  56532. break;
  56533. }
  56534. }
  56535. };
  56536. };
  56537. DracoCompression._GetDefaultDecoderUrl = function () {
  56538. for (var i = 0; i < document.scripts.length; i++) {
  56539. if (document.scripts[i].type === "text/x-draco-decoder") {
  56540. return document.scripts[i].src;
  56541. }
  56542. }
  56543. return null;
  56544. };
  56545. /**
  56546. * Gets the url to the draco decoder if available.
  56547. */
  56548. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  56549. DracoCompression._WorkerBlobUrl = URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  56550. return DracoCompression;
  56551. }());
  56552. BABYLON.DracoCompression = DracoCompression;
  56553. })(BABYLON || (BABYLON = {}));
  56554. //# sourceMappingURL=babylon.dracoCompression.js.map
  56555. var BABYLON;
  56556. (function (BABYLON) {
  56557. var AudioEngine = /** @class */ (function () {
  56558. function AudioEngine() {
  56559. this._audioContext = null;
  56560. this._audioContextInitialized = false;
  56561. this.canUseWebAudio = false;
  56562. this.WarnedWebAudioUnsupported = false;
  56563. this.unlocked = false;
  56564. this.isMP3supported = false;
  56565. this.isOGGsupported = false;
  56566. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  56567. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  56568. this.canUseWebAudio = true;
  56569. }
  56570. var audioElem = document.createElement('audio');
  56571. try {
  56572. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  56573. this.isMP3supported = true;
  56574. }
  56575. }
  56576. catch (e) {
  56577. // protect error during capability check.
  56578. }
  56579. try {
  56580. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  56581. this.isOGGsupported = true;
  56582. }
  56583. }
  56584. catch (e) {
  56585. // protect error during capability check.
  56586. }
  56587. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  56588. this._unlockiOSaudio();
  56589. }
  56590. else {
  56591. this.unlocked = true;
  56592. }
  56593. }
  56594. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  56595. get: function () {
  56596. if (!this._audioContextInitialized) {
  56597. this._initializeAudioContext();
  56598. }
  56599. return this._audioContext;
  56600. },
  56601. enumerable: true,
  56602. configurable: true
  56603. });
  56604. AudioEngine.prototype._unlockiOSaudio = function () {
  56605. var _this = this;
  56606. var unlockaudio = function () {
  56607. if (!_this.audioContext) {
  56608. return;
  56609. }
  56610. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  56611. var source = _this.audioContext.createBufferSource();
  56612. source.buffer = buffer;
  56613. source.connect(_this.audioContext.destination);
  56614. source.start(0);
  56615. setTimeout(function () {
  56616. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  56617. _this.unlocked = true;
  56618. window.removeEventListener('touchend', unlockaudio, false);
  56619. if (_this.onAudioUnlocked) {
  56620. _this.onAudioUnlocked();
  56621. }
  56622. }
  56623. }, 0);
  56624. };
  56625. window.addEventListener('touchend', unlockaudio, false);
  56626. };
  56627. AudioEngine.prototype._initializeAudioContext = function () {
  56628. try {
  56629. if (this.canUseWebAudio) {
  56630. this._audioContext = new AudioContext();
  56631. // create a global volume gain node
  56632. this.masterGain = this._audioContext.createGain();
  56633. this.masterGain.gain.value = 1;
  56634. this.masterGain.connect(this._audioContext.destination);
  56635. this._audioContextInitialized = true;
  56636. }
  56637. }
  56638. catch (e) {
  56639. this.canUseWebAudio = false;
  56640. BABYLON.Tools.Error("Web Audio: " + e.message);
  56641. }
  56642. };
  56643. AudioEngine.prototype.dispose = function () {
  56644. if (this.canUseWebAudio && this._audioContextInitialized) {
  56645. if (this._connectedAnalyser && this._audioContext) {
  56646. this._connectedAnalyser.stopDebugCanvas();
  56647. this._connectedAnalyser.dispose();
  56648. this.masterGain.disconnect();
  56649. this.masterGain.connect(this._audioContext.destination);
  56650. this._connectedAnalyser = null;
  56651. }
  56652. this.masterGain.gain.value = 1;
  56653. }
  56654. this.WarnedWebAudioUnsupported = false;
  56655. };
  56656. AudioEngine.prototype.getGlobalVolume = function () {
  56657. if (this.canUseWebAudio && this._audioContextInitialized) {
  56658. return this.masterGain.gain.value;
  56659. }
  56660. else {
  56661. return -1;
  56662. }
  56663. };
  56664. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  56665. if (this.canUseWebAudio && this._audioContextInitialized) {
  56666. this.masterGain.gain.value = newVolume;
  56667. }
  56668. };
  56669. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  56670. if (this._connectedAnalyser) {
  56671. this._connectedAnalyser.stopDebugCanvas();
  56672. }
  56673. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  56674. this._connectedAnalyser = analyser;
  56675. this.masterGain.disconnect();
  56676. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  56677. }
  56678. };
  56679. return AudioEngine;
  56680. }());
  56681. BABYLON.AudioEngine = AudioEngine;
  56682. })(BABYLON || (BABYLON = {}));
  56683. //# sourceMappingURL=babylon.audioEngine.js.map
  56684. var BABYLON;
  56685. (function (BABYLON) {
  56686. var Sound = /** @class */ (function () {
  56687. /**
  56688. * Create a sound and attach it to a scene
  56689. * @param name Name of your sound
  56690. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  56691. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  56692. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  56693. */
  56694. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  56695. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  56696. var _this = this;
  56697. this.autoplay = false;
  56698. this.loop = false;
  56699. this.useCustomAttenuation = false;
  56700. this.spatialSound = false;
  56701. this.refDistance = 1;
  56702. this.rolloffFactor = 1;
  56703. this.maxDistance = 100;
  56704. this.distanceModel = "linear";
  56705. this._panningModel = "equalpower";
  56706. this._playbackRate = 1;
  56707. this._streaming = false;
  56708. this._startTime = 0;
  56709. this._startOffset = 0;
  56710. this._position = BABYLON.Vector3.Zero();
  56711. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  56712. this._volume = 1;
  56713. this._isReadyToPlay = false;
  56714. this.isPlaying = false;
  56715. this.isPaused = false;
  56716. this._isDirectional = false;
  56717. // Used if you'd like to create a directional sound.
  56718. // If not set, the sound will be omnidirectional
  56719. this._coneInnerAngle = 360;
  56720. this._coneOuterAngle = 360;
  56721. this._coneOuterGain = 0;
  56722. this._isOutputConnected = false;
  56723. this._urlType = "Unknown";
  56724. this.name = name;
  56725. this._scene = scene;
  56726. this._readyToPlayCallback = readyToPlayCallback;
  56727. // Default custom attenuation function is a linear attenuation
  56728. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  56729. if (currentDistance < maxDistance) {
  56730. return currentVolume * (1 - currentDistance / maxDistance);
  56731. }
  56732. else {
  56733. return 0;
  56734. }
  56735. };
  56736. if (options) {
  56737. this.autoplay = options.autoplay || false;
  56738. this.loop = options.loop || false;
  56739. // if volume === 0, we need another way to check this option
  56740. if (options.volume !== undefined) {
  56741. this._volume = options.volume;
  56742. }
  56743. this.spatialSound = options.spatialSound || false;
  56744. this.maxDistance = options.maxDistance || 100;
  56745. this.useCustomAttenuation = options.useCustomAttenuation || false;
  56746. this.rolloffFactor = options.rolloffFactor || 1;
  56747. this.refDistance = options.refDistance || 1;
  56748. this.distanceModel = options.distanceModel || "linear";
  56749. this._playbackRate = options.playbackRate || 1;
  56750. this._streaming = options.streaming || false;
  56751. }
  56752. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56753. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  56754. this._soundGain.gain.value = this._volume;
  56755. this._inputAudioNode = this._soundGain;
  56756. this._ouputAudioNode = this._soundGain;
  56757. if (this.spatialSound) {
  56758. this._createSpatialParameters();
  56759. }
  56760. this._scene.mainSoundTrack.AddSound(this);
  56761. var validParameter = true;
  56762. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  56763. if (urlOrArrayBuffer) {
  56764. if (typeof (urlOrArrayBuffer) === "string")
  56765. this._urlType = "String";
  56766. if (Array.isArray(urlOrArrayBuffer))
  56767. this._urlType = "Array";
  56768. if (urlOrArrayBuffer instanceof ArrayBuffer)
  56769. this._urlType = "ArrayBuffer";
  56770. var urls = [];
  56771. var codecSupportedFound = false;
  56772. switch (this._urlType) {
  56773. case "ArrayBuffer":
  56774. if (urlOrArrayBuffer.byteLength > 0) {
  56775. codecSupportedFound = true;
  56776. this._soundLoaded(urlOrArrayBuffer);
  56777. }
  56778. break;
  56779. case "String":
  56780. urls.push(urlOrArrayBuffer);
  56781. case "Array":
  56782. if (urls.length === 0)
  56783. urls = urlOrArrayBuffer;
  56784. // If we found a supported format, we load it immediately and stop the loop
  56785. for (var i = 0; i < urls.length; i++) {
  56786. var url = urls[i];
  56787. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  56788. codecSupportedFound = true;
  56789. }
  56790. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  56791. codecSupportedFound = true;
  56792. }
  56793. if (url.indexOf(".wav", url.length - 4) !== -1) {
  56794. codecSupportedFound = true;
  56795. }
  56796. if (url.indexOf("blob:") !== -1) {
  56797. codecSupportedFound = true;
  56798. }
  56799. if (codecSupportedFound) {
  56800. // Loading sound using XHR2
  56801. if (!this._streaming) {
  56802. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  56803. }
  56804. else {
  56805. this._htmlAudioElement = new Audio(url);
  56806. this._htmlAudioElement.controls = false;
  56807. this._htmlAudioElement.loop = this.loop;
  56808. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  56809. this._htmlAudioElement.preload = "auto";
  56810. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  56811. _this._isReadyToPlay = true;
  56812. if (_this.autoplay) {
  56813. _this.play();
  56814. }
  56815. if (_this._readyToPlayCallback) {
  56816. _this._readyToPlayCallback();
  56817. }
  56818. });
  56819. document.body.appendChild(this._htmlAudioElement);
  56820. }
  56821. break;
  56822. }
  56823. }
  56824. break;
  56825. default:
  56826. validParameter = false;
  56827. break;
  56828. }
  56829. if (!validParameter) {
  56830. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  56831. }
  56832. else {
  56833. if (!codecSupportedFound) {
  56834. this._isReadyToPlay = true;
  56835. // Simulating a ready to play event to avoid breaking code path
  56836. if (this._readyToPlayCallback) {
  56837. window.setTimeout(function () {
  56838. if (_this._readyToPlayCallback) {
  56839. _this._readyToPlayCallback();
  56840. }
  56841. }, 1000);
  56842. }
  56843. }
  56844. }
  56845. }
  56846. }
  56847. else {
  56848. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  56849. this._scene.mainSoundTrack.AddSound(this);
  56850. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  56851. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  56852. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  56853. }
  56854. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  56855. if (this._readyToPlayCallback) {
  56856. window.setTimeout(function () {
  56857. if (_this._readyToPlayCallback) {
  56858. _this._readyToPlayCallback();
  56859. }
  56860. }, 1000);
  56861. }
  56862. }
  56863. }
  56864. Sound.prototype.dispose = function () {
  56865. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  56866. if (this.isPlaying) {
  56867. this.stop();
  56868. }
  56869. this._isReadyToPlay = false;
  56870. if (this.soundTrackId === -1) {
  56871. this._scene.mainSoundTrack.RemoveSound(this);
  56872. }
  56873. else {
  56874. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  56875. }
  56876. if (this._soundGain) {
  56877. this._soundGain.disconnect();
  56878. this._soundGain = null;
  56879. }
  56880. if (this._soundPanner) {
  56881. this._soundPanner.disconnect();
  56882. this._soundPanner = null;
  56883. }
  56884. if (this._soundSource) {
  56885. this._soundSource.disconnect();
  56886. this._soundSource = null;
  56887. }
  56888. this._audioBuffer = null;
  56889. if (this._htmlAudioElement) {
  56890. this._htmlAudioElement.pause();
  56891. this._htmlAudioElement.src = "";
  56892. document.body.removeChild(this._htmlAudioElement);
  56893. }
  56894. if (this._connectedMesh && this._registerFunc) {
  56895. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56896. this._connectedMesh = null;
  56897. }
  56898. }
  56899. };
  56900. Sound.prototype.isReady = function () {
  56901. return this._isReadyToPlay;
  56902. };
  56903. Sound.prototype._soundLoaded = function (audioData) {
  56904. var _this = this;
  56905. if (!BABYLON.Engine.audioEngine.audioContext) {
  56906. return;
  56907. }
  56908. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  56909. _this._audioBuffer = buffer;
  56910. _this._isReadyToPlay = true;
  56911. if (_this.autoplay) {
  56912. _this.play();
  56913. }
  56914. if (_this._readyToPlayCallback) {
  56915. _this._readyToPlayCallback();
  56916. }
  56917. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  56918. };
  56919. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  56920. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56921. this._audioBuffer = audioBuffer;
  56922. this._isReadyToPlay = true;
  56923. }
  56924. };
  56925. Sound.prototype.updateOptions = function (options) {
  56926. if (options) {
  56927. this.loop = options.loop || this.loop;
  56928. this.maxDistance = options.maxDistance || this.maxDistance;
  56929. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  56930. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  56931. this.refDistance = options.refDistance || this.refDistance;
  56932. this.distanceModel = options.distanceModel || this.distanceModel;
  56933. this._playbackRate = options.playbackRate || this._playbackRate;
  56934. this._updateSpatialParameters();
  56935. if (this.isPlaying) {
  56936. if (this._streaming) {
  56937. this._htmlAudioElement.playbackRate = this._playbackRate;
  56938. }
  56939. else {
  56940. if (this._soundSource) {
  56941. this._soundSource.playbackRate.value = this._playbackRate;
  56942. }
  56943. }
  56944. }
  56945. }
  56946. };
  56947. Sound.prototype._createSpatialParameters = function () {
  56948. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56949. if (this._scene.headphone) {
  56950. this._panningModel = "HRTF";
  56951. }
  56952. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  56953. this._updateSpatialParameters();
  56954. this._soundPanner.connect(this._ouputAudioNode);
  56955. this._inputAudioNode = this._soundPanner;
  56956. }
  56957. };
  56958. Sound.prototype._updateSpatialParameters = function () {
  56959. if (this.spatialSound && this._soundPanner) {
  56960. if (this.useCustomAttenuation) {
  56961. // Tricks to disable in a way embedded Web Audio attenuation
  56962. this._soundPanner.distanceModel = "linear";
  56963. this._soundPanner.maxDistance = Number.MAX_VALUE;
  56964. this._soundPanner.refDistance = 1;
  56965. this._soundPanner.rolloffFactor = 1;
  56966. this._soundPanner.panningModel = this._panningModel;
  56967. }
  56968. else {
  56969. this._soundPanner.distanceModel = this.distanceModel;
  56970. this._soundPanner.maxDistance = this.maxDistance;
  56971. this._soundPanner.refDistance = this.refDistance;
  56972. this._soundPanner.rolloffFactor = this.rolloffFactor;
  56973. this._soundPanner.panningModel = this._panningModel;
  56974. }
  56975. }
  56976. };
  56977. Sound.prototype.switchPanningModelToHRTF = function () {
  56978. this._panningModel = "HRTF";
  56979. this._switchPanningModel();
  56980. };
  56981. Sound.prototype.switchPanningModelToEqualPower = function () {
  56982. this._panningModel = "equalpower";
  56983. this._switchPanningModel();
  56984. };
  56985. Sound.prototype._switchPanningModel = function () {
  56986. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  56987. this._soundPanner.panningModel = this._panningModel;
  56988. }
  56989. };
  56990. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  56991. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56992. if (this._isOutputConnected) {
  56993. this._ouputAudioNode.disconnect();
  56994. }
  56995. this._ouputAudioNode.connect(soundTrackAudioNode);
  56996. this._isOutputConnected = true;
  56997. }
  56998. };
  56999. /**
  57000. * Transform this sound into a directional source
  57001. * @param coneInnerAngle Size of the inner cone in degree
  57002. * @param coneOuterAngle Size of the outer cone in degree
  57003. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  57004. */
  57005. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  57006. if (coneOuterAngle < coneInnerAngle) {
  57007. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  57008. return;
  57009. }
  57010. this._coneInnerAngle = coneInnerAngle;
  57011. this._coneOuterAngle = coneOuterAngle;
  57012. this._coneOuterGain = coneOuterGain;
  57013. this._isDirectional = true;
  57014. if (this.isPlaying && this.loop) {
  57015. this.stop();
  57016. this.play();
  57017. }
  57018. };
  57019. Sound.prototype.setPosition = function (newPosition) {
  57020. this._position = newPosition;
  57021. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  57022. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  57023. }
  57024. };
  57025. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  57026. this._localDirection = newLocalDirection;
  57027. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  57028. this._updateDirection();
  57029. }
  57030. };
  57031. Sound.prototype._updateDirection = function () {
  57032. if (!this._connectedMesh || !this._soundPanner) {
  57033. return;
  57034. }
  57035. var mat = this._connectedMesh.getWorldMatrix();
  57036. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  57037. direction.normalize();
  57038. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  57039. };
  57040. Sound.prototype.updateDistanceFromListener = function () {
  57041. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  57042. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  57043. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  57044. }
  57045. };
  57046. Sound.prototype.setAttenuationFunction = function (callback) {
  57047. this._customAttenuationFunction = callback;
  57048. };
  57049. /**
  57050. * Play the sound
  57051. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  57052. * @param offset (optional) Start the sound setting it at a specific time
  57053. */
  57054. Sound.prototype.play = function (time, offset) {
  57055. var _this = this;
  57056. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  57057. try {
  57058. if (this._startOffset < 0) {
  57059. time = -this._startOffset;
  57060. this._startOffset = 0;
  57061. }
  57062. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  57063. if (!this._soundSource || !this._streamingSource) {
  57064. if (this.spatialSound && this._soundPanner) {
  57065. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  57066. if (this._isDirectional) {
  57067. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  57068. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  57069. this._soundPanner.coneOuterGain = this._coneOuterGain;
  57070. if (this._connectedMesh) {
  57071. this._updateDirection();
  57072. }
  57073. else {
  57074. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  57075. }
  57076. }
  57077. }
  57078. }
  57079. if (this._streaming) {
  57080. if (!this._streamingSource) {
  57081. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  57082. this._htmlAudioElement.onended = function () { _this._onended(); };
  57083. this._htmlAudioElement.playbackRate = this._playbackRate;
  57084. }
  57085. this._streamingSource.disconnect();
  57086. this._streamingSource.connect(this._inputAudioNode);
  57087. this._htmlAudioElement.play();
  57088. }
  57089. else {
  57090. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  57091. this._soundSource.buffer = this._audioBuffer;
  57092. this._soundSource.connect(this._inputAudioNode);
  57093. this._soundSource.loop = this.loop;
  57094. this._soundSource.playbackRate.value = this._playbackRate;
  57095. this._soundSource.onended = function () { _this._onended(); };
  57096. if (this._soundSource.buffer) {
  57097. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  57098. }
  57099. }
  57100. this._startTime = startTime;
  57101. this.isPlaying = true;
  57102. this.isPaused = false;
  57103. }
  57104. catch (ex) {
  57105. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  57106. }
  57107. }
  57108. };
  57109. Sound.prototype._onended = function () {
  57110. this.isPlaying = false;
  57111. if (this.onended) {
  57112. this.onended();
  57113. }
  57114. };
  57115. /**
  57116. * Stop the sound
  57117. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  57118. */
  57119. Sound.prototype.stop = function (time) {
  57120. if (this.isPlaying) {
  57121. if (this._streaming) {
  57122. this._htmlAudioElement.pause();
  57123. // Test needed for Firefox or it will generate an Invalid State Error
  57124. if (this._htmlAudioElement.currentTime > 0) {
  57125. this._htmlAudioElement.currentTime = 0;
  57126. }
  57127. }
  57128. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  57129. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  57130. this._soundSource.stop(stopTime);
  57131. this._soundSource.onended = function () { };
  57132. if (!this.isPaused) {
  57133. this._startOffset = 0;
  57134. }
  57135. }
  57136. this.isPlaying = false;
  57137. }
  57138. };
  57139. Sound.prototype.pause = function () {
  57140. if (this.isPlaying) {
  57141. this.isPaused = true;
  57142. if (this._streaming) {
  57143. this._htmlAudioElement.pause();
  57144. }
  57145. else if (BABYLON.Engine.audioEngine.audioContext) {
  57146. this.stop(0);
  57147. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  57148. }
  57149. }
  57150. };
  57151. Sound.prototype.setVolume = function (newVolume, time) {
  57152. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  57153. if (time && BABYLON.Engine.audioEngine.audioContext) {
  57154. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  57155. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  57156. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  57157. }
  57158. else {
  57159. this._soundGain.gain.value = newVolume;
  57160. }
  57161. }
  57162. this._volume = newVolume;
  57163. };
  57164. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  57165. this._playbackRate = newPlaybackRate;
  57166. if (this.isPlaying) {
  57167. if (this._streaming) {
  57168. this._htmlAudioElement.playbackRate = this._playbackRate;
  57169. }
  57170. else if (this._soundSource) {
  57171. this._soundSource.playbackRate.value = this._playbackRate;
  57172. }
  57173. }
  57174. };
  57175. Sound.prototype.getVolume = function () {
  57176. return this._volume;
  57177. };
  57178. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  57179. var _this = this;
  57180. if (this._connectedMesh && this._registerFunc) {
  57181. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57182. this._registerFunc = null;
  57183. }
  57184. this._connectedMesh = meshToConnectTo;
  57185. if (!this.spatialSound) {
  57186. this.spatialSound = true;
  57187. this._createSpatialParameters();
  57188. if (this.isPlaying && this.loop) {
  57189. this.stop();
  57190. this.play();
  57191. }
  57192. }
  57193. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  57194. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  57195. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  57196. };
  57197. Sound.prototype.detachFromMesh = function () {
  57198. if (this._connectedMesh && this._registerFunc) {
  57199. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57200. this._registerFunc = null;
  57201. this._connectedMesh = null;
  57202. }
  57203. };
  57204. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  57205. if (!node.getBoundingInfo) {
  57206. return;
  57207. }
  57208. var mesh = node;
  57209. var boundingInfo = mesh.getBoundingInfo();
  57210. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  57211. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  57212. this._updateDirection();
  57213. }
  57214. };
  57215. Sound.prototype.clone = function () {
  57216. var _this = this;
  57217. if (!this._streaming) {
  57218. var setBufferAndRun = function () {
  57219. if (_this._isReadyToPlay) {
  57220. clonedSound._audioBuffer = _this.getAudioBuffer();
  57221. clonedSound._isReadyToPlay = true;
  57222. if (clonedSound.autoplay) {
  57223. clonedSound.play();
  57224. }
  57225. }
  57226. else {
  57227. window.setTimeout(setBufferAndRun, 300);
  57228. }
  57229. };
  57230. var currentOptions = {
  57231. autoplay: this.autoplay, loop: this.loop,
  57232. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  57233. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  57234. refDistance: this.refDistance, distanceModel: this.distanceModel
  57235. };
  57236. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  57237. if (this.useCustomAttenuation) {
  57238. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  57239. }
  57240. clonedSound.setPosition(this._position);
  57241. clonedSound.setPlaybackRate(this._playbackRate);
  57242. setBufferAndRun();
  57243. return clonedSound;
  57244. }
  57245. else {
  57246. return null;
  57247. }
  57248. };
  57249. Sound.prototype.getAudioBuffer = function () {
  57250. return this._audioBuffer;
  57251. };
  57252. Sound.prototype.serialize = function () {
  57253. var serializationObject = {
  57254. name: this.name,
  57255. url: this.name,
  57256. autoplay: this.autoplay,
  57257. loop: this.loop,
  57258. volume: this._volume,
  57259. spatialSound: this.spatialSound,
  57260. maxDistance: this.maxDistance,
  57261. rolloffFactor: this.rolloffFactor,
  57262. refDistance: this.refDistance,
  57263. distanceModel: this.distanceModel,
  57264. playbackRate: this._playbackRate,
  57265. panningModel: this._panningModel,
  57266. soundTrackId: this.soundTrackId
  57267. };
  57268. if (this.spatialSound) {
  57269. if (this._connectedMesh)
  57270. serializationObject.connectedMeshId = this._connectedMesh.id;
  57271. serializationObject.position = this._position.asArray();
  57272. serializationObject.refDistance = this.refDistance;
  57273. serializationObject.distanceModel = this.distanceModel;
  57274. serializationObject.isDirectional = this._isDirectional;
  57275. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  57276. serializationObject.coneInnerAngle = this._coneInnerAngle;
  57277. serializationObject.coneOuterAngle = this._coneOuterAngle;
  57278. serializationObject.coneOuterGain = this._coneOuterGain;
  57279. }
  57280. return serializationObject;
  57281. };
  57282. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  57283. var soundName = parsedSound.name;
  57284. var soundUrl;
  57285. if (parsedSound.url) {
  57286. soundUrl = rootUrl + parsedSound.url;
  57287. }
  57288. else {
  57289. soundUrl = rootUrl + soundName;
  57290. }
  57291. var options = {
  57292. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  57293. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  57294. rolloffFactor: parsedSound.rolloffFactor,
  57295. refDistance: parsedSound.refDistance,
  57296. distanceModel: parsedSound.distanceModel,
  57297. playbackRate: parsedSound.playbackRate
  57298. };
  57299. var newSound;
  57300. if (!sourceSound) {
  57301. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  57302. scene._addPendingData(newSound);
  57303. }
  57304. else {
  57305. var setBufferAndRun = function () {
  57306. if (sourceSound._isReadyToPlay) {
  57307. newSound._audioBuffer = sourceSound.getAudioBuffer();
  57308. newSound._isReadyToPlay = true;
  57309. if (newSound.autoplay) {
  57310. newSound.play();
  57311. }
  57312. }
  57313. else {
  57314. window.setTimeout(setBufferAndRun, 300);
  57315. }
  57316. };
  57317. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  57318. setBufferAndRun();
  57319. }
  57320. if (parsedSound.position) {
  57321. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  57322. newSound.setPosition(soundPosition);
  57323. }
  57324. if (parsedSound.isDirectional) {
  57325. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  57326. if (parsedSound.localDirectionToMesh) {
  57327. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  57328. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  57329. }
  57330. }
  57331. if (parsedSound.connectedMeshId) {
  57332. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  57333. if (connectedMesh) {
  57334. newSound.attachToMesh(connectedMesh);
  57335. }
  57336. }
  57337. return newSound;
  57338. };
  57339. return Sound;
  57340. }());
  57341. BABYLON.Sound = Sound;
  57342. })(BABYLON || (BABYLON = {}));
  57343. //# sourceMappingURL=babylon.sound.js.map
  57344. var BABYLON;
  57345. (function (BABYLON) {
  57346. var SoundTrack = /** @class */ (function () {
  57347. function SoundTrack(scene, options) {
  57348. this.id = -1;
  57349. this._isMainTrack = false;
  57350. this._isInitialized = false;
  57351. this._scene = scene;
  57352. this.soundCollection = new Array();
  57353. this._options = options;
  57354. if (!this._isMainTrack) {
  57355. this._scene.soundTracks.push(this);
  57356. this.id = this._scene.soundTracks.length - 1;
  57357. }
  57358. }
  57359. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  57360. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57361. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  57362. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  57363. if (this._options) {
  57364. if (this._options.volume) {
  57365. this._outputAudioNode.gain.value = this._options.volume;
  57366. }
  57367. if (this._options.mainTrack) {
  57368. this._isMainTrack = this._options.mainTrack;
  57369. }
  57370. }
  57371. this._isInitialized = true;
  57372. }
  57373. };
  57374. SoundTrack.prototype.dispose = function () {
  57375. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  57376. if (this._connectedAnalyser) {
  57377. this._connectedAnalyser.stopDebugCanvas();
  57378. }
  57379. while (this.soundCollection.length) {
  57380. this.soundCollection[0].dispose();
  57381. }
  57382. if (this._outputAudioNode) {
  57383. this._outputAudioNode.disconnect();
  57384. }
  57385. this._outputAudioNode = null;
  57386. }
  57387. };
  57388. SoundTrack.prototype.AddSound = function (sound) {
  57389. if (!this._isInitialized) {
  57390. this._initializeSoundTrackAudioGraph();
  57391. }
  57392. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57393. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  57394. }
  57395. if (sound.soundTrackId) {
  57396. if (sound.soundTrackId === -1) {
  57397. this._scene.mainSoundTrack.RemoveSound(sound);
  57398. }
  57399. else {
  57400. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  57401. }
  57402. }
  57403. this.soundCollection.push(sound);
  57404. sound.soundTrackId = this.id;
  57405. };
  57406. SoundTrack.prototype.RemoveSound = function (sound) {
  57407. var index = this.soundCollection.indexOf(sound);
  57408. if (index !== -1) {
  57409. this.soundCollection.splice(index, 1);
  57410. }
  57411. };
  57412. SoundTrack.prototype.setVolume = function (newVolume) {
  57413. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57414. this._outputAudioNode.gain.value = newVolume;
  57415. }
  57416. };
  57417. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  57418. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57419. for (var i = 0; i < this.soundCollection.length; i++) {
  57420. this.soundCollection[i].switchPanningModelToHRTF();
  57421. }
  57422. }
  57423. };
  57424. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  57425. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57426. for (var i = 0; i < this.soundCollection.length; i++) {
  57427. this.soundCollection[i].switchPanningModelToEqualPower();
  57428. }
  57429. }
  57430. };
  57431. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  57432. if (this._connectedAnalyser) {
  57433. this._connectedAnalyser.stopDebugCanvas();
  57434. }
  57435. this._connectedAnalyser = analyser;
  57436. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57437. this._outputAudioNode.disconnect();
  57438. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  57439. }
  57440. };
  57441. return SoundTrack;
  57442. }());
  57443. BABYLON.SoundTrack = SoundTrack;
  57444. })(BABYLON || (BABYLON = {}));
  57445. //# sourceMappingURL=babylon.soundtrack.js.map
  57446. var BABYLON;
  57447. (function (BABYLON) {
  57448. var Analyser = /** @class */ (function () {
  57449. function Analyser(scene) {
  57450. this.SMOOTHING = 0.75;
  57451. this.FFT_SIZE = 512;
  57452. this.BARGRAPHAMPLITUDE = 256;
  57453. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  57454. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  57455. this._scene = scene;
  57456. this._audioEngine = BABYLON.Engine.audioEngine;
  57457. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  57458. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  57459. this._webAudioAnalyser.minDecibels = -140;
  57460. this._webAudioAnalyser.maxDecibels = 0;
  57461. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57462. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57463. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  57464. }
  57465. }
  57466. Analyser.prototype.getFrequencyBinCount = function () {
  57467. if (this._audioEngine.canUseWebAudio) {
  57468. return this._webAudioAnalyser.frequencyBinCount;
  57469. }
  57470. else {
  57471. return 0;
  57472. }
  57473. };
  57474. Analyser.prototype.getByteFrequencyData = function () {
  57475. if (this._audioEngine.canUseWebAudio) {
  57476. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57477. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57478. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  57479. }
  57480. return this._byteFreqs;
  57481. };
  57482. Analyser.prototype.getByteTimeDomainData = function () {
  57483. if (this._audioEngine.canUseWebAudio) {
  57484. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57485. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57486. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  57487. }
  57488. return this._byteTime;
  57489. };
  57490. Analyser.prototype.getFloatFrequencyData = function () {
  57491. if (this._audioEngine.canUseWebAudio) {
  57492. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57493. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57494. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  57495. }
  57496. return this._floatFreqs;
  57497. };
  57498. Analyser.prototype.drawDebugCanvas = function () {
  57499. var _this = this;
  57500. if (this._audioEngine.canUseWebAudio) {
  57501. if (!this._debugCanvas) {
  57502. this._debugCanvas = document.createElement("canvas");
  57503. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  57504. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  57505. this._debugCanvas.style.position = "absolute";
  57506. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  57507. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  57508. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  57509. document.body.appendChild(this._debugCanvas);
  57510. this._registerFunc = function () {
  57511. _this.drawDebugCanvas();
  57512. };
  57513. this._scene.registerBeforeRender(this._registerFunc);
  57514. }
  57515. if (this._registerFunc && this._debugCanvasContext) {
  57516. var workingArray = this.getByteFrequencyData();
  57517. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  57518. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  57519. // Draw the frequency domain chart.
  57520. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  57521. var value = workingArray[i];
  57522. var percent = value / this.BARGRAPHAMPLITUDE;
  57523. var height = this.DEBUGCANVASSIZE.height * percent;
  57524. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  57525. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  57526. var hue = i / this.getFrequencyBinCount() * 360;
  57527. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  57528. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  57529. }
  57530. }
  57531. }
  57532. };
  57533. Analyser.prototype.stopDebugCanvas = function () {
  57534. if (this._debugCanvas) {
  57535. if (this._registerFunc) {
  57536. this._scene.unregisterBeforeRender(this._registerFunc);
  57537. this._registerFunc = null;
  57538. }
  57539. document.body.removeChild(this._debugCanvas);
  57540. this._debugCanvas = null;
  57541. this._debugCanvasContext = null;
  57542. }
  57543. };
  57544. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  57545. if (this._audioEngine.canUseWebAudio) {
  57546. inputAudioNode.connect(this._webAudioAnalyser);
  57547. this._webAudioAnalyser.connect(outputAudioNode);
  57548. }
  57549. };
  57550. Analyser.prototype.dispose = function () {
  57551. if (this._audioEngine.canUseWebAudio) {
  57552. this._webAudioAnalyser.disconnect();
  57553. }
  57554. };
  57555. return Analyser;
  57556. }());
  57557. BABYLON.Analyser = Analyser;
  57558. })(BABYLON || (BABYLON = {}));
  57559. //# sourceMappingURL=babylon.analyser.js.map
  57560. var BABYLON;
  57561. (function (BABYLON) {
  57562. var CubeTexture = /** @class */ (function (_super) {
  57563. __extends(CubeTexture, _super);
  57564. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  57565. if (extensions === void 0) { extensions = null; }
  57566. if (noMipmap === void 0) { noMipmap = false; }
  57567. if (files === void 0) { files = null; }
  57568. if (onLoad === void 0) { onLoad = null; }
  57569. if (onError === void 0) { onError = null; }
  57570. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  57571. if (prefiltered === void 0) { prefiltered = false; }
  57572. if (forcedExtension === void 0) { forcedExtension = null; }
  57573. var _this = _super.call(this, scene) || this;
  57574. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  57575. /**
  57576. * Gets or sets the center of the bounding box associated with the cube texture
  57577. * It must define where the camera used to render the texture was set
  57578. */
  57579. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  57580. _this.name = rootUrl;
  57581. _this.url = rootUrl;
  57582. _this._noMipmap = noMipmap;
  57583. _this.hasAlpha = false;
  57584. _this._format = format;
  57585. _this._prefiltered = prefiltered;
  57586. _this.isCube = true;
  57587. _this._textureMatrix = BABYLON.Matrix.Identity();
  57588. if (prefiltered) {
  57589. _this.gammaSpace = false;
  57590. }
  57591. if (!rootUrl && !files) {
  57592. return _this;
  57593. }
  57594. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  57595. var lastDot = rootUrl.lastIndexOf(".");
  57596. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  57597. var isDDS = (extension === ".dds");
  57598. if (!files) {
  57599. if (!isDDS && !extensions) {
  57600. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  57601. }
  57602. files = [];
  57603. if (extensions) {
  57604. for (var index = 0; index < extensions.length; index++) {
  57605. files.push(rootUrl + extensions[index]);
  57606. }
  57607. }
  57608. }
  57609. _this._files = files;
  57610. if (!_this._texture) {
  57611. if (!scene.useDelayedTextureLoading) {
  57612. if (prefiltered) {
  57613. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  57614. }
  57615. else {
  57616. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  57617. }
  57618. }
  57619. else {
  57620. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  57621. }
  57622. }
  57623. else if (onLoad) {
  57624. if (_this._texture.isReady) {
  57625. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  57626. }
  57627. else {
  57628. _this._texture.onLoadedObservable.add(onLoad);
  57629. }
  57630. }
  57631. return _this;
  57632. }
  57633. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  57634. get: function () {
  57635. return this._boundingBoxSize;
  57636. },
  57637. /**
  57638. * Gets or sets the size of the bounding box associated with the cube texture
  57639. * When defined, the cubemap will switch to local mode
  57640. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  57641. * @example https://www.babylonjs-playground.com/#RNASML
  57642. */
  57643. set: function (value) {
  57644. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  57645. return;
  57646. }
  57647. this._boundingBoxSize = value;
  57648. var scene = this.getScene();
  57649. if (scene) {
  57650. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  57651. }
  57652. },
  57653. enumerable: true,
  57654. configurable: true
  57655. });
  57656. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  57657. var rootUrlKey = "";
  57658. files.forEach(function (url) { return rootUrlKey += url; });
  57659. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  57660. };
  57661. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  57662. if (forcedExtension === void 0) { forcedExtension = null; }
  57663. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  57664. };
  57665. // Methods
  57666. CubeTexture.prototype.delayLoad = function () {
  57667. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  57668. return;
  57669. }
  57670. var scene = this.getScene();
  57671. if (!scene) {
  57672. return;
  57673. }
  57674. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  57675. this._texture = this._getFromCache(this.url, this._noMipmap);
  57676. if (!this._texture) {
  57677. if (this._prefiltered) {
  57678. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  57679. }
  57680. else {
  57681. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  57682. }
  57683. }
  57684. };
  57685. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  57686. return this._textureMatrix;
  57687. };
  57688. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  57689. this._textureMatrix = value;
  57690. };
  57691. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  57692. var texture = BABYLON.SerializationHelper.Parse(function () {
  57693. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  57694. }, parsedTexture, scene);
  57695. // Local Cubemaps
  57696. if (parsedTexture.boundingBoxPosition) {
  57697. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  57698. }
  57699. if (parsedTexture.boundingBoxSize) {
  57700. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  57701. }
  57702. // Animations
  57703. if (parsedTexture.animations) {
  57704. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  57705. var parsedAnimation = parsedTexture.animations[animationIndex];
  57706. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57707. }
  57708. }
  57709. return texture;
  57710. };
  57711. CubeTexture.prototype.clone = function () {
  57712. var _this = this;
  57713. return BABYLON.SerializationHelper.Clone(function () {
  57714. var scene = _this.getScene();
  57715. if (!scene) {
  57716. return _this;
  57717. }
  57718. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  57719. }, this);
  57720. };
  57721. return CubeTexture;
  57722. }(BABYLON.BaseTexture));
  57723. BABYLON.CubeTexture = CubeTexture;
  57724. })(BABYLON || (BABYLON = {}));
  57725. //# sourceMappingURL=babylon.cubeTexture.js.map
  57726. var BABYLON;
  57727. (function (BABYLON) {
  57728. var RenderTargetTexture = /** @class */ (function (_super) {
  57729. __extends(RenderTargetTexture, _super);
  57730. /**
  57731. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  57732. * or used a shadow, depth texture...
  57733. * @param name The friendly name of the texture
  57734. * @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)
  57735. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  57736. * @param generateMipMaps True if mip maps need to be generated after render.
  57737. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  57738. * @param type The type of the buffer in the RTT (int, half float, float...)
  57739. * @param isCube True if a cube texture needs to be created
  57740. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  57741. * @param generateDepthBuffer True to generate a depth buffer
  57742. * @param generateStencilBuffer True to generate a stencil buffer
  57743. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  57744. */
  57745. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  57746. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  57747. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57748. if (isCube === void 0) { isCube = false; }
  57749. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57750. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  57751. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  57752. if (isMulti === void 0) { isMulti = false; }
  57753. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  57754. _this.isCube = isCube;
  57755. /**
  57756. * Use this list to define the list of mesh you want to render.
  57757. */
  57758. _this.renderList = new Array();
  57759. _this.renderParticles = true;
  57760. _this.renderSprites = false;
  57761. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  57762. _this.ignoreCameraViewport = false;
  57763. // Events
  57764. /**
  57765. * An event triggered when the texture is unbind.
  57766. * @type {BABYLON.Observable}
  57767. */
  57768. _this.onBeforeBindObservable = new BABYLON.Observable();
  57769. /**
  57770. * An event triggered when the texture is unbind.
  57771. * @type {BABYLON.Observable}
  57772. */
  57773. _this.onAfterUnbindObservable = new BABYLON.Observable();
  57774. /**
  57775. * An event triggered before rendering the texture
  57776. * @type {BABYLON.Observable}
  57777. */
  57778. _this.onBeforeRenderObservable = new BABYLON.Observable();
  57779. /**
  57780. * An event triggered after rendering the texture
  57781. * @type {BABYLON.Observable}
  57782. */
  57783. _this.onAfterRenderObservable = new BABYLON.Observable();
  57784. /**
  57785. * An event triggered after the texture clear
  57786. * @type {BABYLON.Observable}
  57787. */
  57788. _this.onClearObservable = new BABYLON.Observable();
  57789. _this._currentRefreshId = -1;
  57790. _this._refreshRate = 1;
  57791. _this._samples = 1;
  57792. /**
  57793. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  57794. * It must define where the camera used to render the texture is set
  57795. */
  57796. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  57797. scene = _this.getScene();
  57798. if (!scene) {
  57799. return _this;
  57800. }
  57801. _this._engine = scene.getEngine();
  57802. _this.name = name;
  57803. _this.isRenderTarget = true;
  57804. _this._initialSizeParameter = size;
  57805. _this._processSizeParameter(size);
  57806. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  57807. });
  57808. _this._generateMipMaps = generateMipMaps ? true : false;
  57809. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  57810. // Rendering groups
  57811. _this._renderingManager = new BABYLON.RenderingManager(scene);
  57812. if (isMulti) {
  57813. return _this;
  57814. }
  57815. _this._renderTargetOptions = {
  57816. generateMipMaps: generateMipMaps,
  57817. type: type,
  57818. samplingMode: samplingMode,
  57819. generateDepthBuffer: generateDepthBuffer,
  57820. generateStencilBuffer: generateStencilBuffer
  57821. };
  57822. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  57823. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57824. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57825. }
  57826. if (isCube) {
  57827. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  57828. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  57829. _this._textureMatrix = BABYLON.Matrix.Identity();
  57830. }
  57831. else {
  57832. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  57833. }
  57834. return _this;
  57835. }
  57836. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  57837. get: function () {
  57838. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  57839. },
  57840. enumerable: true,
  57841. configurable: true
  57842. });
  57843. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  57844. get: function () {
  57845. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  57846. },
  57847. enumerable: true,
  57848. configurable: true
  57849. });
  57850. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  57851. get: function () {
  57852. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  57853. },
  57854. enumerable: true,
  57855. configurable: true
  57856. });
  57857. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  57858. set: function (callback) {
  57859. if (this._onAfterUnbindObserver) {
  57860. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  57861. }
  57862. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  57863. },
  57864. enumerable: true,
  57865. configurable: true
  57866. });
  57867. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  57868. set: function (callback) {
  57869. if (this._onBeforeRenderObserver) {
  57870. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  57871. }
  57872. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  57873. },
  57874. enumerable: true,
  57875. configurable: true
  57876. });
  57877. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  57878. set: function (callback) {
  57879. if (this._onAfterRenderObserver) {
  57880. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  57881. }
  57882. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  57883. },
  57884. enumerable: true,
  57885. configurable: true
  57886. });
  57887. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  57888. set: function (callback) {
  57889. if (this._onClearObserver) {
  57890. this.onClearObservable.remove(this._onClearObserver);
  57891. }
  57892. this._onClearObserver = this.onClearObservable.add(callback);
  57893. },
  57894. enumerable: true,
  57895. configurable: true
  57896. });
  57897. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  57898. get: function () {
  57899. return this._renderTargetOptions;
  57900. },
  57901. enumerable: true,
  57902. configurable: true
  57903. });
  57904. RenderTargetTexture.prototype._onRatioRescale = function () {
  57905. if (this._sizeRatio) {
  57906. this.resize(this._initialSizeParameter);
  57907. }
  57908. };
  57909. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  57910. get: function () {
  57911. return this._boundingBoxSize;
  57912. },
  57913. /**
  57914. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  57915. * When defined, the cubemap will switch to local mode
  57916. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  57917. * @example https://www.babylonjs-playground.com/#RNASML
  57918. */
  57919. set: function (value) {
  57920. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  57921. return;
  57922. }
  57923. this._boundingBoxSize = value;
  57924. var scene = this.getScene();
  57925. if (scene) {
  57926. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  57927. }
  57928. },
  57929. enumerable: true,
  57930. configurable: true
  57931. });
  57932. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  57933. if (size.ratio) {
  57934. this._sizeRatio = size.ratio;
  57935. this._size = {
  57936. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  57937. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  57938. };
  57939. }
  57940. else {
  57941. this._size = size;
  57942. }
  57943. };
  57944. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  57945. get: function () {
  57946. return this._samples;
  57947. },
  57948. set: function (value) {
  57949. if (this._samples === value) {
  57950. return;
  57951. }
  57952. var scene = this.getScene();
  57953. if (!scene) {
  57954. return;
  57955. }
  57956. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  57957. },
  57958. enumerable: true,
  57959. configurable: true
  57960. });
  57961. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  57962. this._currentRefreshId = -1;
  57963. };
  57964. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  57965. get: function () {
  57966. return this._refreshRate;
  57967. },
  57968. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  57969. set: function (value) {
  57970. this._refreshRate = value;
  57971. this.resetRefreshCounter();
  57972. },
  57973. enumerable: true,
  57974. configurable: true
  57975. });
  57976. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  57977. if (!this._postProcessManager) {
  57978. var scene = this.getScene();
  57979. if (!scene) {
  57980. return;
  57981. }
  57982. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  57983. this._postProcesses = new Array();
  57984. }
  57985. this._postProcesses.push(postProcess);
  57986. this._postProcesses[0].autoClear = false;
  57987. };
  57988. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  57989. if (!this._postProcesses) {
  57990. return;
  57991. }
  57992. if (dispose) {
  57993. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  57994. var postProcess = _a[_i];
  57995. postProcess.dispose();
  57996. }
  57997. }
  57998. this._postProcesses = [];
  57999. };
  58000. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  58001. if (!this._postProcesses) {
  58002. return;
  58003. }
  58004. var index = this._postProcesses.indexOf(postProcess);
  58005. if (index === -1) {
  58006. return;
  58007. }
  58008. this._postProcesses.splice(index, 1);
  58009. if (this._postProcesses.length > 0) {
  58010. this._postProcesses[0].autoClear = false;
  58011. }
  58012. };
  58013. RenderTargetTexture.prototype._shouldRender = function () {
  58014. if (this._currentRefreshId === -1) {
  58015. this._currentRefreshId = 1;
  58016. return true;
  58017. }
  58018. if (this.refreshRate === this._currentRefreshId) {
  58019. this._currentRefreshId = 1;
  58020. return true;
  58021. }
  58022. this._currentRefreshId++;
  58023. return false;
  58024. };
  58025. RenderTargetTexture.prototype.getRenderSize = function () {
  58026. if (this._size.width) {
  58027. return this._size.width;
  58028. }
  58029. return this._size;
  58030. };
  58031. RenderTargetTexture.prototype.getRenderWidth = function () {
  58032. if (this._size.width) {
  58033. return this._size.width;
  58034. }
  58035. return this._size;
  58036. };
  58037. RenderTargetTexture.prototype.getRenderHeight = function () {
  58038. if (this._size.width) {
  58039. return this._size.height;
  58040. }
  58041. return this._size;
  58042. };
  58043. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  58044. get: function () {
  58045. return true;
  58046. },
  58047. enumerable: true,
  58048. configurable: true
  58049. });
  58050. RenderTargetTexture.prototype.scale = function (ratio) {
  58051. var newSize = this.getRenderSize() * ratio;
  58052. this.resize(newSize);
  58053. };
  58054. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  58055. if (this.isCube) {
  58056. return this._textureMatrix;
  58057. }
  58058. return _super.prototype.getReflectionTextureMatrix.call(this);
  58059. };
  58060. RenderTargetTexture.prototype.resize = function (size) {
  58061. this.releaseInternalTexture();
  58062. var scene = this.getScene();
  58063. if (!scene) {
  58064. return;
  58065. }
  58066. this._processSizeParameter(size);
  58067. if (this.isCube) {
  58068. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  58069. }
  58070. else {
  58071. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  58072. }
  58073. };
  58074. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  58075. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  58076. if (dumpForDebug === void 0) { dumpForDebug = false; }
  58077. var scene = this.getScene();
  58078. if (!scene) {
  58079. return;
  58080. }
  58081. var engine = scene.getEngine();
  58082. if (this.useCameraPostProcesses !== undefined) {
  58083. useCameraPostProcess = this.useCameraPostProcesses;
  58084. }
  58085. if (this._waitingRenderList) {
  58086. this.renderList = [];
  58087. for (var index = 0; index < this._waitingRenderList.length; index++) {
  58088. var id = this._waitingRenderList[index];
  58089. var mesh_1 = scene.getMeshByID(id);
  58090. if (mesh_1) {
  58091. this.renderList.push(mesh_1);
  58092. }
  58093. }
  58094. delete this._waitingRenderList;
  58095. }
  58096. // Is predicate defined?
  58097. if (this.renderListPredicate) {
  58098. if (this.renderList) {
  58099. this.renderList.splice(0); // Clear previous renderList
  58100. }
  58101. else {
  58102. this.renderList = [];
  58103. }
  58104. var scene = this.getScene();
  58105. if (!scene) {
  58106. return;
  58107. }
  58108. var sceneMeshes = scene.meshes;
  58109. for (var index = 0; index < sceneMeshes.length; index++) {
  58110. var mesh = sceneMeshes[index];
  58111. if (this.renderListPredicate(mesh)) {
  58112. this.renderList.push(mesh);
  58113. }
  58114. }
  58115. }
  58116. this.onBeforeBindObservable.notifyObservers(this);
  58117. // Set custom projection.
  58118. // Needs to be before binding to prevent changing the aspect ratio.
  58119. var camera;
  58120. if (this.activeCamera) {
  58121. camera = this.activeCamera;
  58122. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  58123. if (this.activeCamera !== scene.activeCamera) {
  58124. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  58125. }
  58126. }
  58127. else {
  58128. camera = scene.activeCamera;
  58129. if (camera) {
  58130. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  58131. }
  58132. }
  58133. // Prepare renderingManager
  58134. this._renderingManager.reset();
  58135. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  58136. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  58137. var sceneRenderId = scene.getRenderId();
  58138. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  58139. var mesh = currentRenderList[meshIndex];
  58140. if (mesh) {
  58141. if (!mesh.isReady()) {
  58142. // Reset _currentRefreshId
  58143. this.resetRefreshCounter();
  58144. continue;
  58145. }
  58146. mesh._preActivateForIntermediateRendering(sceneRenderId);
  58147. var isMasked = void 0;
  58148. if (!this.renderList && camera) {
  58149. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  58150. }
  58151. else {
  58152. isMasked = false;
  58153. }
  58154. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  58155. mesh._activate(sceneRenderId);
  58156. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  58157. var subMesh = mesh.subMeshes[subIndex];
  58158. scene._activeIndices.addCount(subMesh.indexCount, false);
  58159. this._renderingManager.dispatch(subMesh, mesh);
  58160. }
  58161. }
  58162. }
  58163. }
  58164. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  58165. var particleSystem = scene.particleSystems[particleIndex];
  58166. var emitter = particleSystem.emitter;
  58167. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  58168. continue;
  58169. }
  58170. if (currentRenderList.indexOf(emitter) >= 0) {
  58171. this._renderingManager.dispatchParticles(particleSystem);
  58172. }
  58173. }
  58174. if (this.isCube) {
  58175. for (var face = 0; face < 6; face++) {
  58176. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  58177. scene.incrementRenderId();
  58178. scene.resetCachedMaterial();
  58179. }
  58180. }
  58181. else {
  58182. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  58183. }
  58184. this.onAfterUnbindObservable.notifyObservers(this);
  58185. if (scene.activeCamera) {
  58186. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  58187. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  58188. }
  58189. engine.setViewport(scene.activeCamera.viewport);
  58190. }
  58191. scene.resetCachedMaterial();
  58192. };
  58193. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  58194. var minimum = 128;
  58195. var x = renderDimension * scale;
  58196. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  58197. // Ensure we don't exceed the render dimension (while staying POT)
  58198. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  58199. };
  58200. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  58201. var _this = this;
  58202. if (!this._texture) {
  58203. return;
  58204. }
  58205. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  58206. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  58207. });
  58208. };
  58209. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  58210. var scene = this.getScene();
  58211. if (!scene) {
  58212. return;
  58213. }
  58214. var engine = scene.getEngine();
  58215. if (!this._texture) {
  58216. return;
  58217. }
  58218. // Bind
  58219. if (this._postProcessManager) {
  58220. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  58221. }
  58222. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  58223. if (this._texture) {
  58224. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  58225. }
  58226. }
  58227. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  58228. // Clear
  58229. if (this.onClearObservable.hasObservers()) {
  58230. this.onClearObservable.notifyObservers(engine);
  58231. }
  58232. else {
  58233. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  58234. }
  58235. if (!this._doNotChangeAspectRatio) {
  58236. scene.updateTransformMatrix(true);
  58237. }
  58238. // Render
  58239. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  58240. if (this._postProcessManager) {
  58241. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  58242. }
  58243. else if (useCameraPostProcess) {
  58244. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  58245. }
  58246. if (!this._doNotChangeAspectRatio) {
  58247. scene.updateTransformMatrix(true);
  58248. }
  58249. // Dump ?
  58250. if (dumpForDebug) {
  58251. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  58252. }
  58253. // Unbind
  58254. if (!this.isCube || faceIndex === 5) {
  58255. if (this.isCube) {
  58256. if (faceIndex === 5) {
  58257. engine.generateMipMapsForCubemap(this._texture);
  58258. }
  58259. }
  58260. this.unbindFrameBuffer(engine, faceIndex);
  58261. }
  58262. else {
  58263. this.onAfterRenderObservable.notifyObservers(faceIndex);
  58264. }
  58265. };
  58266. /**
  58267. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  58268. * This allowed control for front to back rendering or reversly depending of the special needs.
  58269. *
  58270. * @param renderingGroupId The rendering group id corresponding to its index
  58271. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  58272. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  58273. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  58274. */
  58275. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  58276. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  58277. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  58278. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  58279. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  58280. };
  58281. /**
  58282. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  58283. *
  58284. * @param renderingGroupId The rendering group id corresponding to its index
  58285. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  58286. */
  58287. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  58288. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  58289. };
  58290. RenderTargetTexture.prototype.clone = function () {
  58291. var textureSize = this.getSize();
  58292. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  58293. // Base texture
  58294. newTexture.hasAlpha = this.hasAlpha;
  58295. newTexture.level = this.level;
  58296. // RenderTarget Texture
  58297. newTexture.coordinatesMode = this.coordinatesMode;
  58298. if (this.renderList) {
  58299. newTexture.renderList = this.renderList.slice(0);
  58300. }
  58301. return newTexture;
  58302. };
  58303. RenderTargetTexture.prototype.serialize = function () {
  58304. if (!this.name) {
  58305. return null;
  58306. }
  58307. var serializationObject = _super.prototype.serialize.call(this);
  58308. serializationObject.renderTargetSize = this.getRenderSize();
  58309. serializationObject.renderList = [];
  58310. if (this.renderList) {
  58311. for (var index = 0; index < this.renderList.length; index++) {
  58312. serializationObject.renderList.push(this.renderList[index].id);
  58313. }
  58314. }
  58315. return serializationObject;
  58316. };
  58317. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  58318. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  58319. var objBuffer = this.getInternalTexture();
  58320. var scene = this.getScene();
  58321. if (objBuffer && scene) {
  58322. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  58323. }
  58324. };
  58325. RenderTargetTexture.prototype.dispose = function () {
  58326. if (this._postProcessManager) {
  58327. this._postProcessManager.dispose();
  58328. this._postProcessManager = null;
  58329. }
  58330. this.clearPostProcesses(true);
  58331. if (this._resizeObserver) {
  58332. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  58333. this._resizeObserver = null;
  58334. }
  58335. this.renderList = null;
  58336. // Remove from custom render targets
  58337. var scene = this.getScene();
  58338. if (!scene) {
  58339. return;
  58340. }
  58341. var index = scene.customRenderTargets.indexOf(this);
  58342. if (index >= 0) {
  58343. scene.customRenderTargets.splice(index, 1);
  58344. }
  58345. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  58346. var camera = _a[_i];
  58347. index = camera.customRenderTargets.indexOf(this);
  58348. if (index >= 0) {
  58349. camera.customRenderTargets.splice(index, 1);
  58350. }
  58351. }
  58352. _super.prototype.dispose.call(this);
  58353. };
  58354. RenderTargetTexture.prototype._rebuild = function () {
  58355. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  58356. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  58357. }
  58358. if (this._postProcessManager) {
  58359. this._postProcessManager._rebuild();
  58360. }
  58361. };
  58362. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  58363. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  58364. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  58365. return RenderTargetTexture;
  58366. }(BABYLON.Texture));
  58367. BABYLON.RenderTargetTexture = RenderTargetTexture;
  58368. })(BABYLON || (BABYLON = {}));
  58369. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  58370. var BABYLON;
  58371. (function (BABYLON) {
  58372. ;
  58373. var MultiRenderTarget = /** @class */ (function (_super) {
  58374. __extends(MultiRenderTarget, _super);
  58375. function MultiRenderTarget(name, size, count, scene, options) {
  58376. var _this = this;
  58377. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  58378. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  58379. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  58380. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  58381. _this._engine = scene.getEngine();
  58382. if (!_this.isSupported) {
  58383. _this.dispose();
  58384. return;
  58385. }
  58386. var types = [];
  58387. var samplingModes = [];
  58388. for (var i = 0; i < count; i++) {
  58389. if (options && options.types && options.types[i] !== undefined) {
  58390. types.push(options.types[i]);
  58391. }
  58392. else {
  58393. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  58394. }
  58395. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  58396. samplingModes.push(options.samplingModes[i]);
  58397. }
  58398. else {
  58399. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58400. }
  58401. }
  58402. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  58403. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  58404. _this._size = size;
  58405. _this._multiRenderTargetOptions = {
  58406. samplingModes: samplingModes,
  58407. generateMipMaps: generateMipMaps,
  58408. generateDepthBuffer: generateDepthBuffer,
  58409. generateStencilBuffer: generateStencilBuffer,
  58410. generateDepthTexture: generateDepthTexture,
  58411. types: types,
  58412. textureCount: count
  58413. };
  58414. _this._createInternalTextures();
  58415. _this._createTextures();
  58416. return _this;
  58417. }
  58418. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  58419. get: function () {
  58420. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  58421. },
  58422. enumerable: true,
  58423. configurable: true
  58424. });
  58425. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  58426. get: function () {
  58427. return this._textures;
  58428. },
  58429. enumerable: true,
  58430. configurable: true
  58431. });
  58432. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  58433. get: function () {
  58434. return this._textures[this._textures.length - 1];
  58435. },
  58436. enumerable: true,
  58437. configurable: true
  58438. });
  58439. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  58440. set: function (wrap) {
  58441. if (this._textures) {
  58442. for (var i = 0; i < this._textures.length; i++) {
  58443. this._textures[i].wrapU = wrap;
  58444. }
  58445. }
  58446. },
  58447. enumerable: true,
  58448. configurable: true
  58449. });
  58450. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  58451. set: function (wrap) {
  58452. if (this._textures) {
  58453. for (var i = 0; i < this._textures.length; i++) {
  58454. this._textures[i].wrapV = wrap;
  58455. }
  58456. }
  58457. },
  58458. enumerable: true,
  58459. configurable: true
  58460. });
  58461. MultiRenderTarget.prototype._rebuild = function () {
  58462. this.releaseInternalTextures();
  58463. this._createInternalTextures();
  58464. for (var i = 0; i < this._internalTextures.length; i++) {
  58465. var texture = this._textures[i];
  58466. texture._texture = this._internalTextures[i];
  58467. }
  58468. // Keeps references to frame buffer and stencil/depth buffer
  58469. this._texture = this._internalTextures[0];
  58470. };
  58471. MultiRenderTarget.prototype._createInternalTextures = function () {
  58472. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  58473. };
  58474. MultiRenderTarget.prototype._createTextures = function () {
  58475. this._textures = [];
  58476. for (var i = 0; i < this._internalTextures.length; i++) {
  58477. var texture = new BABYLON.Texture(null, this.getScene());
  58478. texture._texture = this._internalTextures[i];
  58479. this._textures.push(texture);
  58480. }
  58481. // Keeps references to frame buffer and stencil/depth buffer
  58482. this._texture = this._internalTextures[0];
  58483. };
  58484. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  58485. get: function () {
  58486. return this._samples;
  58487. },
  58488. set: function (value) {
  58489. if (this._samples === value) {
  58490. return;
  58491. }
  58492. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  58493. },
  58494. enumerable: true,
  58495. configurable: true
  58496. });
  58497. MultiRenderTarget.prototype.resize = function (size) {
  58498. this.releaseInternalTextures();
  58499. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  58500. this._createInternalTextures();
  58501. };
  58502. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  58503. var _this = this;
  58504. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  58505. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  58506. });
  58507. };
  58508. MultiRenderTarget.prototype.dispose = function () {
  58509. this.releaseInternalTextures();
  58510. _super.prototype.dispose.call(this);
  58511. };
  58512. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  58513. if (!this._internalTextures) {
  58514. return;
  58515. }
  58516. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  58517. if (this._internalTextures[i] !== undefined) {
  58518. this._internalTextures[i].dispose();
  58519. this._internalTextures.splice(i, 1);
  58520. }
  58521. }
  58522. };
  58523. return MultiRenderTarget;
  58524. }(BABYLON.RenderTargetTexture));
  58525. BABYLON.MultiRenderTarget = MultiRenderTarget;
  58526. })(BABYLON || (BABYLON = {}));
  58527. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  58528. var BABYLON;
  58529. (function (BABYLON) {
  58530. var MirrorTexture = /** @class */ (function (_super) {
  58531. __extends(MirrorTexture, _super);
  58532. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  58533. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58534. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  58535. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  58536. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  58537. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  58538. _this._transformMatrix = BABYLON.Matrix.Zero();
  58539. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  58540. _this._adaptiveBlurKernel = 0;
  58541. _this._blurKernelX = 0;
  58542. _this._blurKernelY = 0;
  58543. _this._blurRatio = 1.0;
  58544. _this.ignoreCameraViewport = true;
  58545. _this.onBeforeRenderObservable.add(function () {
  58546. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  58547. _this._savedViewMatrix = scene.getViewMatrix();
  58548. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  58549. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  58550. scene.clipPlane = _this.mirrorPlane;
  58551. scene.getEngine().cullBackFaces = false;
  58552. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  58553. });
  58554. _this.onAfterRenderObservable.add(function () {
  58555. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  58556. scene.getEngine().cullBackFaces = true;
  58557. scene._mirroredCameraPosition = null;
  58558. delete scene.clipPlane;
  58559. });
  58560. return _this;
  58561. }
  58562. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  58563. get: function () {
  58564. return this._blurRatio;
  58565. },
  58566. set: function (value) {
  58567. if (this._blurRatio === value) {
  58568. return;
  58569. }
  58570. this._blurRatio = value;
  58571. this._preparePostProcesses();
  58572. },
  58573. enumerable: true,
  58574. configurable: true
  58575. });
  58576. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  58577. set: function (value) {
  58578. this._adaptiveBlurKernel = value;
  58579. this._autoComputeBlurKernel();
  58580. },
  58581. enumerable: true,
  58582. configurable: true
  58583. });
  58584. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  58585. set: function (value) {
  58586. this.blurKernelX = value;
  58587. this.blurKernelY = value;
  58588. },
  58589. enumerable: true,
  58590. configurable: true
  58591. });
  58592. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  58593. get: function () {
  58594. return this._blurKernelX;
  58595. },
  58596. set: function (value) {
  58597. if (this._blurKernelX === value) {
  58598. return;
  58599. }
  58600. this._blurKernelX = value;
  58601. this._preparePostProcesses();
  58602. },
  58603. enumerable: true,
  58604. configurable: true
  58605. });
  58606. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  58607. get: function () {
  58608. return this._blurKernelY;
  58609. },
  58610. set: function (value) {
  58611. if (this._blurKernelY === value) {
  58612. return;
  58613. }
  58614. this._blurKernelY = value;
  58615. this._preparePostProcesses();
  58616. },
  58617. enumerable: true,
  58618. configurable: true
  58619. });
  58620. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  58621. var engine = this.getScene().getEngine();
  58622. var dw = this.getRenderWidth() / engine.getRenderWidth();
  58623. var dh = this.getRenderHeight() / engine.getRenderHeight();
  58624. this.blurKernelX = this._adaptiveBlurKernel * dw;
  58625. this.blurKernelY = this._adaptiveBlurKernel * dh;
  58626. };
  58627. MirrorTexture.prototype._onRatioRescale = function () {
  58628. if (this._sizeRatio) {
  58629. this.resize(this._initialSizeParameter);
  58630. if (!this._adaptiveBlurKernel) {
  58631. this._preparePostProcesses();
  58632. }
  58633. }
  58634. if (this._adaptiveBlurKernel) {
  58635. this._autoComputeBlurKernel();
  58636. }
  58637. };
  58638. MirrorTexture.prototype._preparePostProcesses = function () {
  58639. this.clearPostProcesses(true);
  58640. if (this._blurKernelX && this._blurKernelY) {
  58641. var engine = this.getScene().getEngine();
  58642. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58643. 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);
  58644. this._blurX.autoClear = false;
  58645. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  58646. this._blurX.inputTexture = this._texture;
  58647. }
  58648. else {
  58649. this._blurX.alwaysForcePOT = true;
  58650. }
  58651. 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);
  58652. this._blurY.autoClear = false;
  58653. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  58654. this.addPostProcess(this._blurX);
  58655. this.addPostProcess(this._blurY);
  58656. }
  58657. else {
  58658. if (this._blurY) {
  58659. this.removePostProcess(this._blurY);
  58660. this._blurY.dispose();
  58661. this._blurY = null;
  58662. }
  58663. if (this._blurX) {
  58664. this.removePostProcess(this._blurX);
  58665. this._blurX.dispose();
  58666. this._blurX = null;
  58667. }
  58668. }
  58669. };
  58670. MirrorTexture.prototype.clone = function () {
  58671. var scene = this.getScene();
  58672. if (!scene) {
  58673. return this;
  58674. }
  58675. var textureSize = this.getSize();
  58676. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  58677. // Base texture
  58678. newTexture.hasAlpha = this.hasAlpha;
  58679. newTexture.level = this.level;
  58680. // Mirror Texture
  58681. newTexture.mirrorPlane = this.mirrorPlane.clone();
  58682. if (this.renderList) {
  58683. newTexture.renderList = this.renderList.slice(0);
  58684. }
  58685. return newTexture;
  58686. };
  58687. MirrorTexture.prototype.serialize = function () {
  58688. if (!this.name) {
  58689. return null;
  58690. }
  58691. var serializationObject = _super.prototype.serialize.call(this);
  58692. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  58693. return serializationObject;
  58694. };
  58695. return MirrorTexture;
  58696. }(BABYLON.RenderTargetTexture));
  58697. BABYLON.MirrorTexture = MirrorTexture;
  58698. })(BABYLON || (BABYLON = {}));
  58699. //# sourceMappingURL=babylon.mirrorTexture.js.map
  58700. var BABYLON;
  58701. (function (BABYLON) {
  58702. /**
  58703. * Creates a refraction texture used by refraction channel of the standard material.
  58704. * @param name the texture name
  58705. * @param size size of the underlying texture
  58706. * @param scene root scene
  58707. */
  58708. var RefractionTexture = /** @class */ (function (_super) {
  58709. __extends(RefractionTexture, _super);
  58710. function RefractionTexture(name, size, scene, generateMipMaps) {
  58711. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  58712. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  58713. _this.depth = 2.0;
  58714. _this.onBeforeRenderObservable.add(function () {
  58715. scene.clipPlane = _this.refractionPlane;
  58716. });
  58717. _this.onAfterRenderObservable.add(function () {
  58718. delete scene.clipPlane;
  58719. });
  58720. return _this;
  58721. }
  58722. RefractionTexture.prototype.clone = function () {
  58723. var scene = this.getScene();
  58724. if (!scene) {
  58725. return this;
  58726. }
  58727. var textureSize = this.getSize();
  58728. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  58729. // Base texture
  58730. newTexture.hasAlpha = this.hasAlpha;
  58731. newTexture.level = this.level;
  58732. // Refraction Texture
  58733. newTexture.refractionPlane = this.refractionPlane.clone();
  58734. if (this.renderList) {
  58735. newTexture.renderList = this.renderList.slice(0);
  58736. }
  58737. newTexture.depth = this.depth;
  58738. return newTexture;
  58739. };
  58740. RefractionTexture.prototype.serialize = function () {
  58741. if (!this.name) {
  58742. return null;
  58743. }
  58744. var serializationObject = _super.prototype.serialize.call(this);
  58745. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  58746. serializationObject.depth = this.depth;
  58747. return serializationObject;
  58748. };
  58749. return RefractionTexture;
  58750. }(BABYLON.RenderTargetTexture));
  58751. BABYLON.RefractionTexture = RefractionTexture;
  58752. })(BABYLON || (BABYLON = {}));
  58753. //# sourceMappingURL=babylon.refractionTexture.js.map
  58754. var BABYLON;
  58755. (function (BABYLON) {
  58756. var DynamicTexture = /** @class */ (function (_super) {
  58757. __extends(DynamicTexture, _super);
  58758. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  58759. if (scene === void 0) { scene = null; }
  58760. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58761. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  58762. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  58763. _this.name = name;
  58764. _this._engine = _this.getScene().getEngine();
  58765. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58766. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58767. _this._generateMipMaps = generateMipMaps;
  58768. if (options.getContext) {
  58769. _this._canvas = options;
  58770. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  58771. }
  58772. else {
  58773. _this._canvas = document.createElement("canvas");
  58774. if (options.width) {
  58775. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  58776. }
  58777. else {
  58778. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  58779. }
  58780. }
  58781. var textureSize = _this.getSize();
  58782. _this._canvas.width = textureSize.width;
  58783. _this._canvas.height = textureSize.height;
  58784. _this._context = _this._canvas.getContext("2d");
  58785. return _this;
  58786. }
  58787. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  58788. get: function () {
  58789. return true;
  58790. },
  58791. enumerable: true,
  58792. configurable: true
  58793. });
  58794. DynamicTexture.prototype._recreate = function (textureSize) {
  58795. this._canvas.width = textureSize.width;
  58796. this._canvas.height = textureSize.height;
  58797. this.releaseInternalTexture();
  58798. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  58799. };
  58800. DynamicTexture.prototype.scale = function (ratio) {
  58801. var textureSize = this.getSize();
  58802. textureSize.width *= ratio;
  58803. textureSize.height *= ratio;
  58804. this._recreate(textureSize);
  58805. };
  58806. DynamicTexture.prototype.scaleTo = function (width, height) {
  58807. var textureSize = this.getSize();
  58808. textureSize.width = width;
  58809. textureSize.height = height;
  58810. this._recreate(textureSize);
  58811. };
  58812. DynamicTexture.prototype.getContext = function () {
  58813. return this._context;
  58814. };
  58815. DynamicTexture.prototype.clear = function () {
  58816. var size = this.getSize();
  58817. this._context.fillRect(0, 0, size.width, size.height);
  58818. };
  58819. DynamicTexture.prototype.update = function (invertY) {
  58820. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  58821. };
  58822. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  58823. if (update === void 0) { update = true; }
  58824. var size = this.getSize();
  58825. if (clearColor) {
  58826. this._context.fillStyle = clearColor;
  58827. this._context.fillRect(0, 0, size.width, size.height);
  58828. }
  58829. this._context.font = font;
  58830. if (x === null || x === undefined) {
  58831. var textSize = this._context.measureText(text);
  58832. x = (size.width - textSize.width) / 2;
  58833. }
  58834. if (y === null || y === undefined) {
  58835. var fontSize = parseInt((font.replace(/\D/g, '')));
  58836. ;
  58837. y = (size.height / 2) + (fontSize / 3.65);
  58838. }
  58839. this._context.fillStyle = color;
  58840. this._context.fillText(text, x, y);
  58841. if (update) {
  58842. this.update(invertY);
  58843. }
  58844. };
  58845. DynamicTexture.prototype.clone = function () {
  58846. var scene = this.getScene();
  58847. if (!scene) {
  58848. return this;
  58849. }
  58850. var textureSize = this.getSize();
  58851. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  58852. // Base texture
  58853. newTexture.hasAlpha = this.hasAlpha;
  58854. newTexture.level = this.level;
  58855. // Dynamic Texture
  58856. newTexture.wrapU = this.wrapU;
  58857. newTexture.wrapV = this.wrapV;
  58858. return newTexture;
  58859. };
  58860. DynamicTexture.prototype._rebuild = function () {
  58861. this.update();
  58862. };
  58863. return DynamicTexture;
  58864. }(BABYLON.Texture));
  58865. BABYLON.DynamicTexture = DynamicTexture;
  58866. })(BABYLON || (BABYLON = {}));
  58867. //# sourceMappingURL=babylon.dynamicTexture.js.map
  58868. var BABYLON;
  58869. (function (BABYLON) {
  58870. var VideoTexture = /** @class */ (function (_super) {
  58871. __extends(VideoTexture, _super);
  58872. /**
  58873. * Creates a video texture.
  58874. * Sample : https://doc.babylonjs.com/how_to/video_texture
  58875. * @param {string | null} name optional name, will detect from video source, if not defined
  58876. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  58877. * @param {BABYLON.Scene} scene is obviously the current scene.
  58878. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  58879. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  58880. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  58881. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  58882. */
  58883. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  58884. if (generateMipMaps === void 0) { generateMipMaps = false; }
  58885. if (invertY === void 0) { invertY = false; }
  58886. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58887. if (settings === void 0) { settings = {
  58888. autoPlay: true,
  58889. loop: true,
  58890. autoUpdateTexture: true,
  58891. }; }
  58892. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  58893. _this._createInternalTexture = function () {
  58894. if (_this._texture != null) {
  58895. return;
  58896. }
  58897. if (!_this._engine.needPOTTextures ||
  58898. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  58899. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58900. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58901. }
  58902. else {
  58903. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58904. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58905. _this._generateMipMaps = false;
  58906. }
  58907. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  58908. _this._texture.isReady = true;
  58909. _this._updateInternalTexture();
  58910. };
  58911. _this.reset = function () {
  58912. if (_this._texture == null) {
  58913. return;
  58914. }
  58915. _this._texture.dispose();
  58916. _this._texture = null;
  58917. };
  58918. _this._updateInternalTexture = function (e) {
  58919. if (_this._texture == null || !_this._texture.isReady) {
  58920. return;
  58921. }
  58922. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  58923. return;
  58924. }
  58925. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  58926. };
  58927. _this._engine = _this.getScene().getEngine();
  58928. _this._generateMipMaps = generateMipMaps;
  58929. _this._samplingMode = samplingMode;
  58930. _this.autoUpdateTexture = settings.autoUpdateTexture;
  58931. _this.name = name || _this._getName(src);
  58932. _this.video = _this._getVideo(src);
  58933. if (settings.autoPlay !== undefined) {
  58934. _this.video.autoplay = settings.autoPlay;
  58935. }
  58936. if (settings.loop !== undefined) {
  58937. _this.video.loop = settings.loop;
  58938. }
  58939. _this.video.addEventListener("canplay", _this._createInternalTexture);
  58940. _this.video.addEventListener("paused", _this._updateInternalTexture);
  58941. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  58942. _this.video.addEventListener("emptied", _this.reset);
  58943. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  58944. _this._createInternalTexture();
  58945. }
  58946. return _this;
  58947. }
  58948. VideoTexture.prototype._getName = function (src) {
  58949. if (src instanceof HTMLVideoElement) {
  58950. return src.currentSrc;
  58951. }
  58952. if (typeof src === "object") {
  58953. return src.toString();
  58954. }
  58955. return src;
  58956. };
  58957. ;
  58958. VideoTexture.prototype._getVideo = function (src) {
  58959. if (src instanceof HTMLVideoElement) {
  58960. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  58961. return src;
  58962. }
  58963. var video = document.createElement("video");
  58964. if (typeof src === "string") {
  58965. BABYLON.Tools.SetCorsBehavior(src, video);
  58966. video.src = src;
  58967. }
  58968. else {
  58969. BABYLON.Tools.SetCorsBehavior(src[0], video);
  58970. src.forEach(function (url) {
  58971. var source = document.createElement("source");
  58972. source.src = url;
  58973. video.appendChild(source);
  58974. });
  58975. }
  58976. return video;
  58977. };
  58978. ;
  58979. /**
  58980. * Internal method to initiate `update`.
  58981. */
  58982. VideoTexture.prototype._rebuild = function () {
  58983. this.update();
  58984. };
  58985. /**
  58986. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  58987. */
  58988. VideoTexture.prototype.update = function () {
  58989. if (!this.autoUpdateTexture) {
  58990. // Expecting user to call `updateTexture` manually
  58991. return;
  58992. }
  58993. this.updateTexture(true);
  58994. };
  58995. /**
  58996. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  58997. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  58998. */
  58999. VideoTexture.prototype.updateTexture = function (isVisible) {
  59000. if (!isVisible) {
  59001. return;
  59002. }
  59003. if (this.video.paused) {
  59004. return;
  59005. }
  59006. this._updateInternalTexture();
  59007. };
  59008. /**
  59009. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  59010. * @param url New url.
  59011. */
  59012. VideoTexture.prototype.updateURL = function (url) {
  59013. this.video.src = url;
  59014. };
  59015. VideoTexture.prototype.dispose = function () {
  59016. _super.prototype.dispose.call(this);
  59017. this.video.removeEventListener("canplay", this._createInternalTexture);
  59018. this.video.removeEventListener("paused", this._updateInternalTexture);
  59019. this.video.removeEventListener("seeked", this._updateInternalTexture);
  59020. this.video.removeEventListener("emptied", this.reset);
  59021. this.video.pause();
  59022. };
  59023. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  59024. var video = document.createElement("video");
  59025. var constraintsDeviceId;
  59026. if (constraints && constraints.deviceId) {
  59027. constraintsDeviceId = {
  59028. exact: constraints.deviceId,
  59029. };
  59030. }
  59031. navigator.getUserMedia =
  59032. navigator.getUserMedia ||
  59033. navigator.webkitGetUserMedia ||
  59034. navigator.mozGetUserMedia ||
  59035. navigator.msGetUserMedia;
  59036. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  59037. if (navigator.getUserMedia) {
  59038. navigator.getUserMedia({
  59039. video: {
  59040. deviceId: constraintsDeviceId,
  59041. width: {
  59042. min: (constraints && constraints.minWidth) || 256,
  59043. max: (constraints && constraints.maxWidth) || 640,
  59044. },
  59045. height: {
  59046. min: (constraints && constraints.minHeight) || 256,
  59047. max: (constraints && constraints.maxHeight) || 480,
  59048. },
  59049. },
  59050. }, function (stream) {
  59051. if (video.mozSrcObject !== undefined) {
  59052. // hack for Firefox < 19
  59053. video.mozSrcObject = stream;
  59054. }
  59055. else {
  59056. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  59057. }
  59058. video.play();
  59059. if (onReady) {
  59060. onReady(new VideoTexture("video", video, scene, true, true));
  59061. }
  59062. }, function (e) {
  59063. BABYLON.Tools.Error(e.name);
  59064. });
  59065. }
  59066. };
  59067. return VideoTexture;
  59068. }(BABYLON.Texture));
  59069. BABYLON.VideoTexture = VideoTexture;
  59070. })(BABYLON || (BABYLON = {}));
  59071. //# sourceMappingURL=babylon.videoTexture.js.map
  59072. var BABYLON;
  59073. (function (BABYLON) {
  59074. var RawTexture = /** @class */ (function (_super) {
  59075. __extends(RawTexture, _super);
  59076. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  59077. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59078. if (invertY === void 0) { invertY = false; }
  59079. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59080. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59081. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  59082. _this.format = format;
  59083. _this._engine = scene.getEngine();
  59084. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  59085. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59086. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59087. return _this;
  59088. }
  59089. RawTexture.prototype.update = function (data) {
  59090. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  59091. };
  59092. // Statics
  59093. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59094. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59095. if (invertY === void 0) { invertY = false; }
  59096. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59097. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  59098. };
  59099. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59100. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59101. if (invertY === void 0) { invertY = false; }
  59102. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59103. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  59104. };
  59105. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59106. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59107. if (invertY === void 0) { invertY = false; }
  59108. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59109. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  59110. };
  59111. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  59112. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59113. if (invertY === void 0) { invertY = false; }
  59114. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59115. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59116. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  59117. };
  59118. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  59119. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59120. if (invertY === void 0) { invertY = false; }
  59121. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59122. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59123. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  59124. };
  59125. return RawTexture;
  59126. }(BABYLON.Texture));
  59127. BABYLON.RawTexture = RawTexture;
  59128. })(BABYLON || (BABYLON = {}));
  59129. //# sourceMappingURL=babylon.rawTexture.js.map
  59130. var BABYLON;
  59131. (function (BABYLON) {
  59132. /**
  59133. * PostProcess can be used to apply a shader to a texture after it has been rendered
  59134. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  59135. */
  59136. var PostProcess = /** @class */ (function () {
  59137. /**
  59138. * Creates a new instance of @see PostProcess
  59139. * @param name The name of the PostProcess.
  59140. * @param fragmentUrl The url of the fragment shader to be used.
  59141. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  59142. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  59143. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  59144. * @param camera The camera to apply the render pass to.
  59145. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  59146. * @param engine The engine which the post process will be applied. (default: current engine)
  59147. * @param reusable If the post process can be reused on the same frame. (default: false)
  59148. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  59149. * @param textureType Type of textures used when performing the post process. (default: 0)
  59150. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  59151. * @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
  59152. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  59153. */
  59154. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  59155. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  59156. if (defines === void 0) { defines = null; }
  59157. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59158. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  59159. if (blockCompilation === void 0) { blockCompilation = false; }
  59160. this.name = name;
  59161. /**
  59162. * Width of the texture to apply the post process on
  59163. */
  59164. this.width = -1;
  59165. /**
  59166. * Height of the texture to apply the post process on
  59167. */
  59168. this.height = -1;
  59169. /**
  59170. * If the buffer needs to be cleared before applying the post process. (default: true)
  59171. * Should be set to false if shader will overwrite all previous pixels.
  59172. */
  59173. this.autoClear = true;
  59174. /**
  59175. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  59176. */
  59177. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  59178. /**
  59179. * Animations to be used for the post processing
  59180. */
  59181. this.animations = new Array();
  59182. /**
  59183. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  59184. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  59185. */
  59186. this.enablePixelPerfectMode = false;
  59187. /**
  59188. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  59189. */
  59190. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  59191. /**
  59192. * Force textures to be a power of two (default: false)
  59193. */
  59194. this.alwaysForcePOT = false;
  59195. /**
  59196. * Number of sample textures (default: 1)
  59197. */
  59198. this.samples = 1;
  59199. /**
  59200. * Modify the scale of the post process to be the same as the viewport (default: false)
  59201. */
  59202. this.adaptScaleToCurrentViewport = false;
  59203. this._reusable = false;
  59204. /**
  59205. * Smart array of input and output textures for the post process.
  59206. */
  59207. this._textures = new BABYLON.SmartArray(2);
  59208. /**
  59209. * The index in _textures that corresponds to the output texture.
  59210. */
  59211. this._currentRenderTextureInd = 0;
  59212. this._scaleRatio = new BABYLON.Vector2(1, 1);
  59213. this._texelSize = BABYLON.Vector2.Zero();
  59214. // Events
  59215. /**
  59216. * An event triggered when the postprocess is activated.
  59217. * @type {BABYLON.Observable}
  59218. */
  59219. this.onActivateObservable = new BABYLON.Observable();
  59220. /**
  59221. * An event triggered when the postprocess changes its size.
  59222. * @type {BABYLON.Observable}
  59223. */
  59224. this.onSizeChangedObservable = new BABYLON.Observable();
  59225. /**
  59226. * An event triggered when the postprocess applies its effect.
  59227. * @type {BABYLON.Observable}
  59228. */
  59229. this.onApplyObservable = new BABYLON.Observable();
  59230. /**
  59231. * An event triggered before rendering the postprocess
  59232. * @type {BABYLON.Observable}
  59233. */
  59234. this.onBeforeRenderObservable = new BABYLON.Observable();
  59235. /**
  59236. * An event triggered after rendering the postprocess
  59237. * @type {BABYLON.Observable}
  59238. */
  59239. this.onAfterRenderObservable = new BABYLON.Observable();
  59240. if (camera != null) {
  59241. this._camera = camera;
  59242. this._scene = camera.getScene();
  59243. camera.attachPostProcess(this);
  59244. this._engine = this._scene.getEngine();
  59245. this._scene.postProcesses.push(this);
  59246. }
  59247. else if (engine) {
  59248. this._engine = engine;
  59249. this._engine.postProcesses.push(this);
  59250. }
  59251. this._options = options;
  59252. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  59253. this._reusable = reusable || false;
  59254. this._textureType = textureType;
  59255. this._samplers = samplers || [];
  59256. this._samplers.push("textureSampler");
  59257. this._fragmentUrl = fragmentUrl;
  59258. this._vertexUrl = vertexUrl;
  59259. this._parameters = parameters || [];
  59260. this._parameters.push("scale");
  59261. this._indexParameters = indexParameters;
  59262. if (!blockCompilation) {
  59263. this.updateEffect(defines);
  59264. }
  59265. }
  59266. Object.defineProperty(PostProcess.prototype, "onActivate", {
  59267. /**
  59268. * A function that is added to the onActivateObservable
  59269. */
  59270. set: function (callback) {
  59271. if (this._onActivateObserver) {
  59272. this.onActivateObservable.remove(this._onActivateObserver);
  59273. }
  59274. if (callback) {
  59275. this._onActivateObserver = this.onActivateObservable.add(callback);
  59276. }
  59277. },
  59278. enumerable: true,
  59279. configurable: true
  59280. });
  59281. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  59282. /**
  59283. * A function that is added to the onSizeChangedObservable
  59284. */
  59285. set: function (callback) {
  59286. if (this._onSizeChangedObserver) {
  59287. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  59288. }
  59289. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  59290. },
  59291. enumerable: true,
  59292. configurable: true
  59293. });
  59294. Object.defineProperty(PostProcess.prototype, "onApply", {
  59295. /**
  59296. * A function that is added to the onApplyObservable
  59297. */
  59298. set: function (callback) {
  59299. if (this._onApplyObserver) {
  59300. this.onApplyObservable.remove(this._onApplyObserver);
  59301. }
  59302. this._onApplyObserver = this.onApplyObservable.add(callback);
  59303. },
  59304. enumerable: true,
  59305. configurable: true
  59306. });
  59307. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  59308. /**
  59309. * A function that is added to the onBeforeRenderObservable
  59310. */
  59311. set: function (callback) {
  59312. if (this._onBeforeRenderObserver) {
  59313. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  59314. }
  59315. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  59316. },
  59317. enumerable: true,
  59318. configurable: true
  59319. });
  59320. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  59321. /**
  59322. * A function that is added to the onAfterRenderObservable
  59323. */
  59324. set: function (callback) {
  59325. if (this._onAfterRenderObserver) {
  59326. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  59327. }
  59328. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  59329. },
  59330. enumerable: true,
  59331. configurable: true
  59332. });
  59333. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  59334. /**
  59335. * 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
  59336. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  59337. */
  59338. get: function () {
  59339. return this._textures.data[this._currentRenderTextureInd];
  59340. },
  59341. set: function (value) {
  59342. this._forcedOutputTexture = value;
  59343. },
  59344. enumerable: true,
  59345. configurable: true
  59346. });
  59347. /**
  59348. * Gets the camera which post process is applied to.
  59349. * @returns The camera the post process is applied to.
  59350. */
  59351. PostProcess.prototype.getCamera = function () {
  59352. return this._camera;
  59353. };
  59354. Object.defineProperty(PostProcess.prototype, "texelSize", {
  59355. /**
  59356. * Gets the texel size of the postprocess.
  59357. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  59358. */
  59359. get: function () {
  59360. if (this._shareOutputWithPostProcess) {
  59361. return this._shareOutputWithPostProcess.texelSize;
  59362. }
  59363. if (this._forcedOutputTexture) {
  59364. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  59365. }
  59366. return this._texelSize;
  59367. },
  59368. enumerable: true,
  59369. configurable: true
  59370. });
  59371. /**
  59372. * Gets the engine which this post process belongs to.
  59373. * @returns The engine the post process was enabled with.
  59374. */
  59375. PostProcess.prototype.getEngine = function () {
  59376. return this._engine;
  59377. };
  59378. /**
  59379. * The effect that is created when initializing the post process.
  59380. * @returns The created effect corrisponding the the postprocess.
  59381. */
  59382. PostProcess.prototype.getEffect = function () {
  59383. return this._effect;
  59384. };
  59385. /**
  59386. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  59387. * @param postProcess The post process to share the output with.
  59388. * @returns This post process.
  59389. */
  59390. PostProcess.prototype.shareOutputWith = function (postProcess) {
  59391. this._disposeTextures();
  59392. this._shareOutputWithPostProcess = postProcess;
  59393. return this;
  59394. };
  59395. /**
  59396. * Updates the effect with the current post process compile time values and recompiles the shader.
  59397. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  59398. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  59399. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  59400. * @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
  59401. * @param onCompiled Called when the shader has been compiled.
  59402. * @param onError Called if there is an error when compiling a shader.
  59403. */
  59404. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  59405. if (defines === void 0) { defines = null; }
  59406. if (uniforms === void 0) { uniforms = null; }
  59407. if (samplers === void 0) { samplers = null; }
  59408. 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);
  59409. };
  59410. /**
  59411. * The post process is reusable if it can be used multiple times within one frame.
  59412. * @returns If the post process is reusable
  59413. */
  59414. PostProcess.prototype.isReusable = function () {
  59415. return this._reusable;
  59416. };
  59417. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  59418. PostProcess.prototype.markTextureDirty = function () {
  59419. this.width = -1;
  59420. };
  59421. /**
  59422. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  59423. * 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.
  59424. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  59425. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  59426. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  59427. */
  59428. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  59429. var _this = this;
  59430. if (sourceTexture === void 0) { sourceTexture = null; }
  59431. camera = camera || this._camera;
  59432. var scene = camera.getScene();
  59433. var engine = scene.getEngine();
  59434. var maxSize = engine.getCaps().maxTextureSize;
  59435. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  59436. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  59437. // 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
  59438. var webVRCamera = camera.parent;
  59439. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  59440. requiredWidth /= 2;
  59441. }
  59442. var desiredWidth = (this._options.width || requiredWidth);
  59443. var desiredHeight = this._options.height || requiredHeight;
  59444. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  59445. if (this.adaptScaleToCurrentViewport) {
  59446. var currentViewport = engine.currentViewport;
  59447. if (currentViewport) {
  59448. desiredWidth *= currentViewport.width;
  59449. desiredHeight *= currentViewport.height;
  59450. }
  59451. }
  59452. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  59453. if (!this._options.width) {
  59454. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  59455. }
  59456. if (!this._options.height) {
  59457. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  59458. }
  59459. }
  59460. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  59461. if (this._textures.length > 0) {
  59462. for (var i = 0; i < this._textures.length; i++) {
  59463. this._engine._releaseTexture(this._textures.data[i]);
  59464. }
  59465. this._textures.reset();
  59466. }
  59467. this.width = desiredWidth;
  59468. this.height = desiredHeight;
  59469. var textureSize = { width: this.width, height: this.height };
  59470. var textureOptions = {
  59471. generateMipMaps: false,
  59472. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  59473. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  59474. samplingMode: this.renderTargetSamplingMode,
  59475. type: this._textureType
  59476. };
  59477. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  59478. if (this._reusable) {
  59479. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  59480. }
  59481. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  59482. this.onSizeChangedObservable.notifyObservers(this);
  59483. }
  59484. this._textures.forEach(function (texture) {
  59485. if (texture.samples !== _this.samples) {
  59486. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  59487. }
  59488. });
  59489. }
  59490. var target;
  59491. if (this._shareOutputWithPostProcess) {
  59492. target = this._shareOutputWithPostProcess.inputTexture;
  59493. }
  59494. else if (this._forcedOutputTexture) {
  59495. target = this._forcedOutputTexture;
  59496. this.width = this._forcedOutputTexture.width;
  59497. this.height = this._forcedOutputTexture.height;
  59498. }
  59499. else {
  59500. target = this.inputTexture;
  59501. }
  59502. // Bind the input of this post process to be used as the output of the previous post process.
  59503. if (this.enablePixelPerfectMode) {
  59504. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  59505. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  59506. }
  59507. else {
  59508. this._scaleRatio.copyFromFloats(1, 1);
  59509. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  59510. }
  59511. this.onActivateObservable.notifyObservers(camera);
  59512. // Clear
  59513. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  59514. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  59515. }
  59516. if (this._reusable) {
  59517. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  59518. }
  59519. };
  59520. Object.defineProperty(PostProcess.prototype, "isSupported", {
  59521. /**
  59522. * If the post process is supported.
  59523. */
  59524. get: function () {
  59525. return this._effect.isSupported;
  59526. },
  59527. enumerable: true,
  59528. configurable: true
  59529. });
  59530. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  59531. /**
  59532. * The aspect ratio of the output texture.
  59533. */
  59534. get: function () {
  59535. if (this._shareOutputWithPostProcess) {
  59536. return this._shareOutputWithPostProcess.aspectRatio;
  59537. }
  59538. if (this._forcedOutputTexture) {
  59539. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  59540. }
  59541. return this.width / this.height;
  59542. },
  59543. enumerable: true,
  59544. configurable: true
  59545. });
  59546. /**
  59547. * Get a value indicating if the post-process is ready to be used
  59548. * @returns true if the post-process is ready (shader is compiled)
  59549. */
  59550. PostProcess.prototype.isReady = function () {
  59551. return this._effect && this._effect.isReady();
  59552. };
  59553. /**
  59554. * Binds all textures and uniforms to the shader, this will be run on every pass.
  59555. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  59556. */
  59557. PostProcess.prototype.apply = function () {
  59558. // Check
  59559. if (!this._effect || !this._effect.isReady())
  59560. return null;
  59561. // States
  59562. this._engine.enableEffect(this._effect);
  59563. this._engine.setState(false);
  59564. this._engine.setDepthBuffer(false);
  59565. this._engine.setDepthWrite(false);
  59566. // Alpha
  59567. this._engine.setAlphaMode(this.alphaMode);
  59568. if (this.alphaConstants) {
  59569. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  59570. }
  59571. // Bind the output texture of the preivous post process as the input to this post process.
  59572. var source;
  59573. if (this._shareOutputWithPostProcess) {
  59574. source = this._shareOutputWithPostProcess.inputTexture;
  59575. }
  59576. else if (this._forcedOutputTexture) {
  59577. source = this._forcedOutputTexture;
  59578. }
  59579. else {
  59580. source = this.inputTexture;
  59581. }
  59582. this._effect._bindTexture("textureSampler", source);
  59583. // Parameters
  59584. this._effect.setVector2("scale", this._scaleRatio);
  59585. this.onApplyObservable.notifyObservers(this._effect);
  59586. return this._effect;
  59587. };
  59588. PostProcess.prototype._disposeTextures = function () {
  59589. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  59590. return;
  59591. }
  59592. if (this._textures.length > 0) {
  59593. for (var i = 0; i < this._textures.length; i++) {
  59594. this._engine._releaseTexture(this._textures.data[i]);
  59595. }
  59596. }
  59597. this._textures.dispose();
  59598. };
  59599. /**
  59600. * Disposes the post process.
  59601. * @param camera The camera to dispose the post process on.
  59602. */
  59603. PostProcess.prototype.dispose = function (camera) {
  59604. camera = camera || this._camera;
  59605. this._disposeTextures();
  59606. if (this._scene) {
  59607. var index_1 = this._scene.postProcesses.indexOf(this);
  59608. if (index_1 !== -1) {
  59609. this._scene.postProcesses.splice(index_1, 1);
  59610. }
  59611. }
  59612. else {
  59613. var index_2 = this._engine.postProcesses.indexOf(this);
  59614. if (index_2 !== -1) {
  59615. this._engine.postProcesses.splice(index_2, 1);
  59616. }
  59617. }
  59618. if (!camera) {
  59619. return;
  59620. }
  59621. camera.detachPostProcess(this);
  59622. var index = camera._postProcesses.indexOf(this);
  59623. if (index === 0 && camera._postProcesses.length > 0) {
  59624. this._camera._postProcesses[0].markTextureDirty();
  59625. }
  59626. this.onActivateObservable.clear();
  59627. this.onAfterRenderObservable.clear();
  59628. this.onApplyObservable.clear();
  59629. this.onBeforeRenderObservable.clear();
  59630. this.onSizeChangedObservable.clear();
  59631. };
  59632. return PostProcess;
  59633. }());
  59634. BABYLON.PostProcess = PostProcess;
  59635. })(BABYLON || (BABYLON = {}));
  59636. //# sourceMappingURL=babylon.postProcess.js.map
  59637. var BABYLON;
  59638. (function (BABYLON) {
  59639. var PassPostProcess = /** @class */ (function (_super) {
  59640. __extends(PassPostProcess, _super);
  59641. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59642. if (camera === void 0) { camera = null; }
  59643. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59644. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  59645. }
  59646. return PassPostProcess;
  59647. }(BABYLON.PostProcess));
  59648. BABYLON.PassPostProcess = PassPostProcess;
  59649. })(BABYLON || (BABYLON = {}));
  59650. //# sourceMappingURL=babylon.passPostProcess.js.map
  59651. var __assign = (this && this.__assign) || Object.assign || function(t) {
  59652. for (var s, i = 1, n = arguments.length; i < n; i++) {
  59653. s = arguments[i];
  59654. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  59655. t[p] = s[p];
  59656. }
  59657. return t;
  59658. };
  59659. var BABYLON;
  59660. (function (BABYLON) {
  59661. /**
  59662. * Default implementation of @see IShadowGenerator.
  59663. * This is the main object responsible of generating shadows in the framework.
  59664. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  59665. */
  59666. var ShadowGenerator = /** @class */ (function () {
  59667. /**
  59668. * Creates a ShadowGenerator object.
  59669. * A ShadowGenerator is the required tool to use the shadows.
  59670. * Each light casting shadows needs to use its own ShadowGenerator.
  59671. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  59672. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  59673. * @param light The light object generating the shadows.
  59674. * @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.
  59675. */
  59676. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  59677. this._bias = 0.00005;
  59678. this._blurBoxOffset = 1;
  59679. this._blurScale = 2;
  59680. this._blurKernel = 1;
  59681. this._useKernelBlur = false;
  59682. this._filter = ShadowGenerator.FILTER_NONE;
  59683. this._darkness = 0;
  59684. this._transparencyShadow = false;
  59685. /**
  59686. * Controls the extent to which the shadows fade out at the edge of the frustum
  59687. * Used only by directionals and spots
  59688. */
  59689. this.frustumEdgeFalloff = 0;
  59690. /**
  59691. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  59692. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  59693. * It might on the other hand introduce peter panning.
  59694. */
  59695. this.forceBackFacesOnly = false;
  59696. this._lightDirection = BABYLON.Vector3.Zero();
  59697. this._viewMatrix = BABYLON.Matrix.Zero();
  59698. this._projectionMatrix = BABYLON.Matrix.Zero();
  59699. this._transformMatrix = BABYLON.Matrix.Zero();
  59700. this._currentFaceIndex = 0;
  59701. this._currentFaceIndexCache = 0;
  59702. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  59703. this._mapSize = mapSize;
  59704. this._light = light;
  59705. this._scene = light.getScene();
  59706. light._shadowGenerator = this;
  59707. // Texture type fallback from float to int if not supported.
  59708. var caps = this._scene.getEngine().getCaps();
  59709. if (!useFullFloatFirst) {
  59710. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  59711. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59712. }
  59713. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  59714. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59715. }
  59716. else {
  59717. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59718. }
  59719. }
  59720. else {
  59721. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  59722. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59723. }
  59724. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  59725. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59726. }
  59727. else {
  59728. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59729. }
  59730. }
  59731. this._initializeGenerator();
  59732. }
  59733. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  59734. /**
  59735. * Shadow generator mode None: no filtering applied.
  59736. */
  59737. get: function () {
  59738. return ShadowGenerator._FILTER_NONE;
  59739. },
  59740. enumerable: true,
  59741. configurable: true
  59742. });
  59743. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  59744. /**
  59745. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  59746. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  59747. */
  59748. get: function () {
  59749. return ShadowGenerator._FILTER_POISSONSAMPLING;
  59750. },
  59751. enumerable: true,
  59752. configurable: true
  59753. });
  59754. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  59755. /**
  59756. * Shadow generator mode ESM: Exponential Shadow Mapping.
  59757. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59758. */
  59759. get: function () {
  59760. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  59761. },
  59762. enumerable: true,
  59763. configurable: true
  59764. });
  59765. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  59766. /**
  59767. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  59768. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59769. */
  59770. get: function () {
  59771. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  59772. },
  59773. enumerable: true,
  59774. configurable: true
  59775. });
  59776. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  59777. /**
  59778. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  59779. * edge artifacts on steep falloff.
  59780. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59781. */
  59782. get: function () {
  59783. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  59784. },
  59785. enumerable: true,
  59786. configurable: true
  59787. });
  59788. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  59789. /**
  59790. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  59791. * edge artifacts on steep falloff.
  59792. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59793. */
  59794. get: function () {
  59795. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  59796. },
  59797. enumerable: true,
  59798. configurable: true
  59799. });
  59800. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  59801. /**
  59802. * Gets the bias: offset applied on the depth preventing acnea.
  59803. */
  59804. get: function () {
  59805. return this._bias;
  59806. },
  59807. /**
  59808. * Sets the bias: offset applied on the depth preventing acnea.
  59809. */
  59810. set: function (bias) {
  59811. this._bias = bias;
  59812. },
  59813. enumerable: true,
  59814. configurable: true
  59815. });
  59816. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  59817. /**
  59818. * Gets the blur box offset: offset applied during the blur pass.
  59819. * Only usefull if useKernelBlur = false
  59820. */
  59821. get: function () {
  59822. return this._blurBoxOffset;
  59823. },
  59824. /**
  59825. * Sets the blur box offset: offset applied during the blur pass.
  59826. * Only usefull if useKernelBlur = false
  59827. */
  59828. set: function (value) {
  59829. if (this._blurBoxOffset === value) {
  59830. return;
  59831. }
  59832. this._blurBoxOffset = value;
  59833. this._disposeBlurPostProcesses();
  59834. },
  59835. enumerable: true,
  59836. configurable: true
  59837. });
  59838. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  59839. /**
  59840. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  59841. * 2 means half of the size.
  59842. */
  59843. get: function () {
  59844. return this._blurScale;
  59845. },
  59846. /**
  59847. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  59848. * 2 means half of the size.
  59849. */
  59850. set: function (value) {
  59851. if (this._blurScale === value) {
  59852. return;
  59853. }
  59854. this._blurScale = value;
  59855. this._disposeBlurPostProcesses();
  59856. },
  59857. enumerable: true,
  59858. configurable: true
  59859. });
  59860. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  59861. /**
  59862. * Gets the blur kernel: kernel size of the blur pass.
  59863. * Only usefull if useKernelBlur = true
  59864. */
  59865. get: function () {
  59866. return this._blurKernel;
  59867. },
  59868. /**
  59869. * Sets the blur kernel: kernel size of the blur pass.
  59870. * Only usefull if useKernelBlur = true
  59871. */
  59872. set: function (value) {
  59873. if (this._blurKernel === value) {
  59874. return;
  59875. }
  59876. this._blurKernel = value;
  59877. this._disposeBlurPostProcesses();
  59878. },
  59879. enumerable: true,
  59880. configurable: true
  59881. });
  59882. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  59883. /**
  59884. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  59885. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  59886. */
  59887. get: function () {
  59888. return this._useKernelBlur;
  59889. },
  59890. /**
  59891. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  59892. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  59893. */
  59894. set: function (value) {
  59895. if (this._useKernelBlur === value) {
  59896. return;
  59897. }
  59898. this._useKernelBlur = value;
  59899. this._disposeBlurPostProcesses();
  59900. },
  59901. enumerable: true,
  59902. configurable: true
  59903. });
  59904. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  59905. /**
  59906. * Gets the depth scale used in ESM mode.
  59907. */
  59908. get: function () {
  59909. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  59910. },
  59911. /**
  59912. * Sets the depth scale used in ESM mode.
  59913. * This can override the scale stored on the light.
  59914. */
  59915. set: function (value) {
  59916. this._depthScale = value;
  59917. },
  59918. enumerable: true,
  59919. configurable: true
  59920. });
  59921. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  59922. /**
  59923. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  59924. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  59925. */
  59926. get: function () {
  59927. return this._filter;
  59928. },
  59929. /**
  59930. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  59931. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  59932. */
  59933. set: function (value) {
  59934. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  59935. if (this._light.needCube()) {
  59936. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  59937. this.useExponentialShadowMap = true;
  59938. return;
  59939. }
  59940. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  59941. this.useCloseExponentialShadowMap = true;
  59942. return;
  59943. }
  59944. }
  59945. if (this._filter === value) {
  59946. return;
  59947. }
  59948. this._filter = value;
  59949. this._disposeBlurPostProcesses();
  59950. this._applyFilterValues();
  59951. this._light._markMeshesAsLightDirty();
  59952. },
  59953. enumerable: true,
  59954. configurable: true
  59955. });
  59956. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  59957. /**
  59958. * Gets if the current filter is set to Poisson Sampling aka PCF.
  59959. */
  59960. get: function () {
  59961. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  59962. },
  59963. /**
  59964. * Sets the current filter to Poisson Sampling aka PCF.
  59965. */
  59966. set: function (value) {
  59967. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  59968. return;
  59969. }
  59970. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  59971. },
  59972. enumerable: true,
  59973. configurable: true
  59974. });
  59975. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  59976. /**
  59977. * Gets if the current filter is set to VSM.
  59978. * DEPRECATED. Should use useExponentialShadowMap instead.
  59979. */
  59980. get: function () {
  59981. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  59982. return this.useExponentialShadowMap;
  59983. },
  59984. /**
  59985. * Sets the current filter is to VSM.
  59986. * DEPRECATED. Should use useExponentialShadowMap instead.
  59987. */
  59988. set: function (value) {
  59989. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  59990. this.useExponentialShadowMap = value;
  59991. },
  59992. enumerable: true,
  59993. configurable: true
  59994. });
  59995. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  59996. /**
  59997. * Gets if the current filter is set to blurred VSM.
  59998. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  59999. */
  60000. get: function () {
  60001. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  60002. return this.useBlurExponentialShadowMap;
  60003. },
  60004. /**
  60005. * Sets the current filter is to blurred VSM.
  60006. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  60007. */
  60008. set: function (value) {
  60009. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  60010. this.useBlurExponentialShadowMap = value;
  60011. },
  60012. enumerable: true,
  60013. configurable: true
  60014. });
  60015. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  60016. /**
  60017. * Gets if the current filter is set to ESM.
  60018. */
  60019. get: function () {
  60020. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  60021. },
  60022. /**
  60023. * Sets the current filter is to ESM.
  60024. */
  60025. set: function (value) {
  60026. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  60027. return;
  60028. }
  60029. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60030. },
  60031. enumerable: true,
  60032. configurable: true
  60033. });
  60034. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  60035. /**
  60036. * Gets if the current filter is set to filtered ESM.
  60037. */
  60038. get: function () {
  60039. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  60040. },
  60041. /**
  60042. * Gets if the current filter is set to filtered ESM.
  60043. */
  60044. set: function (value) {
  60045. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  60046. return;
  60047. }
  60048. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60049. },
  60050. enumerable: true,
  60051. configurable: true
  60052. });
  60053. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  60054. /**
  60055. * Gets if the current filter is set to "close ESM" (using the inverse of the
  60056. * exponential to prevent steep falloff artifacts).
  60057. */
  60058. get: function () {
  60059. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  60060. },
  60061. /**
  60062. * Sets the current filter to "close ESM" (using the inverse of the
  60063. * exponential to prevent steep falloff artifacts).
  60064. */
  60065. set: function (value) {
  60066. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  60067. return;
  60068. }
  60069. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60070. },
  60071. enumerable: true,
  60072. configurable: true
  60073. });
  60074. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  60075. /**
  60076. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  60077. * exponential to prevent steep falloff artifacts).
  60078. */
  60079. get: function () {
  60080. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  60081. },
  60082. /**
  60083. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  60084. * exponential to prevent steep falloff artifacts).
  60085. */
  60086. set: function (value) {
  60087. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  60088. return;
  60089. }
  60090. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60091. },
  60092. enumerable: true,
  60093. configurable: true
  60094. });
  60095. /**
  60096. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  60097. * 0 means strongest and 1 would means no shadow.
  60098. * @returns the darkness.
  60099. */
  60100. ShadowGenerator.prototype.getDarkness = function () {
  60101. return this._darkness;
  60102. };
  60103. /**
  60104. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  60105. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  60106. * @returns the shadow generator allowing fluent coding.
  60107. */
  60108. ShadowGenerator.prototype.setDarkness = function (darkness) {
  60109. if (darkness >= 1.0)
  60110. this._darkness = 1.0;
  60111. else if (darkness <= 0.0)
  60112. this._darkness = 0.0;
  60113. else
  60114. this._darkness = darkness;
  60115. return this;
  60116. };
  60117. /**
  60118. * Sets the ability to have transparent shadow (boolean).
  60119. * @param transparent True if transparent else False
  60120. * @returns the shadow generator allowing fluent coding
  60121. */
  60122. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  60123. this._transparencyShadow = transparent;
  60124. return this;
  60125. };
  60126. /**
  60127. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  60128. * @returns The render target texture if present otherwise, null
  60129. */
  60130. ShadowGenerator.prototype.getShadowMap = function () {
  60131. return this._shadowMap;
  60132. };
  60133. /**
  60134. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  60135. * @returns The render target texture if the shadow map is present otherwise, null
  60136. */
  60137. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  60138. if (this._shadowMap2) {
  60139. return this._shadowMap2;
  60140. }
  60141. return this._shadowMap;
  60142. };
  60143. /**
  60144. * Helper function to add a mesh and its descendants to the list of shadow casters.
  60145. * @param mesh Mesh to add
  60146. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  60147. * @returns the Shadow Generator itself
  60148. */
  60149. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  60150. if (includeDescendants === void 0) { includeDescendants = true; }
  60151. if (!this._shadowMap) {
  60152. return this;
  60153. }
  60154. if (!this._shadowMap.renderList) {
  60155. this._shadowMap.renderList = [];
  60156. }
  60157. this._shadowMap.renderList.push(mesh);
  60158. if (includeDescendants) {
  60159. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  60160. }
  60161. return this;
  60162. var _a;
  60163. };
  60164. /**
  60165. * Helper function to remove a mesh and its descendants from the list of shadow casters
  60166. * @param mesh Mesh to remove
  60167. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  60168. * @returns the Shadow Generator itself
  60169. */
  60170. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  60171. if (includeDescendants === void 0) { includeDescendants = true; }
  60172. if (!this._shadowMap || !this._shadowMap.renderList) {
  60173. return this;
  60174. }
  60175. var index = this._shadowMap.renderList.indexOf(mesh);
  60176. if (index !== -1) {
  60177. this._shadowMap.renderList.splice(index, 1);
  60178. }
  60179. if (includeDescendants) {
  60180. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  60181. var child = _a[_i];
  60182. this.removeShadowCaster(child);
  60183. }
  60184. }
  60185. return this;
  60186. };
  60187. /**
  60188. * Returns the associated light object.
  60189. * @returns the light generating the shadow
  60190. */
  60191. ShadowGenerator.prototype.getLight = function () {
  60192. return this._light;
  60193. };
  60194. ShadowGenerator.prototype._initializeGenerator = function () {
  60195. this._light._markMeshesAsLightDirty();
  60196. this._initializeShadowMap();
  60197. };
  60198. ShadowGenerator.prototype._initializeShadowMap = function () {
  60199. var _this = this;
  60200. // Render target
  60201. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  60202. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60203. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60204. this._shadowMap.anisotropicFilteringLevel = 1;
  60205. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60206. this._shadowMap.renderParticles = false;
  60207. this._shadowMap.ignoreCameraViewport = true;
  60208. // Record Face Index before render.
  60209. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  60210. _this._currentFaceIndex = faceIndex;
  60211. });
  60212. // Custom render function.
  60213. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  60214. // Blur if required afer render.
  60215. this._shadowMap.onAfterUnbindObservable.add(function () {
  60216. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  60217. return;
  60218. }
  60219. var shadowMap = _this.getShadowMapForRendering();
  60220. if (shadowMap) {
  60221. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  60222. }
  60223. });
  60224. // Clear according to the chosen filter.
  60225. this._shadowMap.onClearObservable.add(function (engine) {
  60226. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  60227. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  60228. }
  60229. else {
  60230. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  60231. }
  60232. });
  60233. };
  60234. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  60235. var _this = this;
  60236. var engine = this._scene.getEngine();
  60237. var targetSize = this._mapSize / this.blurScale;
  60238. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  60239. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  60240. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60241. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60242. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60243. }
  60244. if (this.useKernelBlur) {
  60245. 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);
  60246. this._kernelBlurXPostprocess.width = targetSize;
  60247. this._kernelBlurXPostprocess.height = targetSize;
  60248. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  60249. effect.setTexture("textureSampler", _this._shadowMap);
  60250. });
  60251. 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);
  60252. this._kernelBlurXPostprocess.autoClear = false;
  60253. this._kernelBlurYPostprocess.autoClear = false;
  60254. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60255. this._kernelBlurXPostprocess.packedFloat = true;
  60256. this._kernelBlurYPostprocess.packedFloat = true;
  60257. }
  60258. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  60259. }
  60260. else {
  60261. 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);
  60262. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  60263. effect.setFloat2("screenSize", targetSize, targetSize);
  60264. effect.setTexture("textureSampler", _this._shadowMap);
  60265. });
  60266. this._boxBlurPostprocess.autoClear = false;
  60267. this._blurPostProcesses = [this._boxBlurPostprocess];
  60268. }
  60269. };
  60270. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  60271. var index;
  60272. var engine = this._scene.getEngine();
  60273. if (depthOnlySubMeshes.length) {
  60274. engine.setColorWrite(false);
  60275. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  60276. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  60277. }
  60278. engine.setColorWrite(true);
  60279. }
  60280. for (index = 0; index < opaqueSubMeshes.length; index++) {
  60281. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  60282. }
  60283. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  60284. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  60285. }
  60286. if (this._transparencyShadow) {
  60287. for (index = 0; index < transparentSubMeshes.length; index++) {
  60288. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  60289. }
  60290. }
  60291. };
  60292. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  60293. var _this = this;
  60294. var mesh = subMesh.getRenderingMesh();
  60295. var scene = this._scene;
  60296. var engine = scene.getEngine();
  60297. var material = subMesh.getMaterial();
  60298. if (!material) {
  60299. return;
  60300. }
  60301. // Culling
  60302. engine.setState(material.backFaceCulling);
  60303. // Managing instances
  60304. var batch = mesh._getInstancesRenderList(subMesh._id);
  60305. if (batch.mustReturn) {
  60306. return;
  60307. }
  60308. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  60309. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  60310. engine.enableEffect(this._effect);
  60311. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  60312. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  60313. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  60314. this._effect.setVector3("lightPosition", this.getLight().position);
  60315. if (scene.activeCamera) {
  60316. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  60317. }
  60318. // Alpha test
  60319. if (material && material.needAlphaTesting()) {
  60320. var alphaTexture = material.getAlphaTestTexture();
  60321. if (alphaTexture) {
  60322. this._effect.setTexture("diffuseSampler", alphaTexture);
  60323. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  60324. }
  60325. }
  60326. // Bones
  60327. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60328. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  60329. }
  60330. if (this.forceBackFacesOnly) {
  60331. engine.setState(true, 0, false, true);
  60332. }
  60333. // Draw
  60334. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  60335. if (this.forceBackFacesOnly) {
  60336. engine.setState(true, 0, false, false);
  60337. }
  60338. }
  60339. else {
  60340. // Need to reset refresh rate of the shadowMap
  60341. if (this._shadowMap) {
  60342. this._shadowMap.resetRefreshCounter();
  60343. }
  60344. }
  60345. };
  60346. ShadowGenerator.prototype._applyFilterValues = function () {
  60347. if (!this._shadowMap) {
  60348. return;
  60349. }
  60350. if (this.filter === ShadowGenerator.FILTER_NONE) {
  60351. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  60352. }
  60353. else {
  60354. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60355. }
  60356. };
  60357. /**
  60358. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  60359. * @param onCompiled Callback triggered at the and of the effects compilation
  60360. * @param options Sets of optional options forcing the compilation with different modes
  60361. */
  60362. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  60363. var _this = this;
  60364. var localOptions = __assign({ useInstances: false }, options);
  60365. var shadowMap = this.getShadowMap();
  60366. if (!shadowMap) {
  60367. if (onCompiled) {
  60368. onCompiled(this);
  60369. }
  60370. return;
  60371. }
  60372. var renderList = shadowMap.renderList;
  60373. if (!renderList) {
  60374. if (onCompiled) {
  60375. onCompiled(this);
  60376. }
  60377. return;
  60378. }
  60379. var subMeshes = new Array();
  60380. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  60381. var mesh = renderList_1[_i];
  60382. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  60383. }
  60384. if (subMeshes.length === 0) {
  60385. if (onCompiled) {
  60386. onCompiled(this);
  60387. }
  60388. return;
  60389. }
  60390. var currentIndex = 0;
  60391. var checkReady = function () {
  60392. if (!_this._scene || !_this._scene.getEngine()) {
  60393. return;
  60394. }
  60395. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  60396. currentIndex++;
  60397. if (currentIndex >= subMeshes.length) {
  60398. if (onCompiled) {
  60399. onCompiled(_this);
  60400. }
  60401. return;
  60402. }
  60403. }
  60404. setTimeout(checkReady, 16);
  60405. };
  60406. checkReady();
  60407. };
  60408. /**
  60409. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  60410. * @param options Sets of optional options forcing the compilation with different modes
  60411. * @returns A promise that resolves when the compilation completes
  60412. */
  60413. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  60414. var _this = this;
  60415. return new Promise(function (resolve) {
  60416. _this.forceCompilation(function () {
  60417. resolve();
  60418. }, options);
  60419. });
  60420. };
  60421. /**
  60422. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  60423. * @param subMesh The submesh we want to render in the shadow map
  60424. * @param useInstances Defines wether will draw in the map using instances
  60425. * @returns true if ready otherwise, false
  60426. */
  60427. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  60428. var defines = [];
  60429. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60430. defines.push("#define FLOAT");
  60431. }
  60432. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  60433. defines.push("#define ESM");
  60434. }
  60435. var attribs = [BABYLON.VertexBuffer.PositionKind];
  60436. var mesh = subMesh.getMesh();
  60437. var material = subMesh.getMaterial();
  60438. // Alpha test
  60439. if (material && material.needAlphaTesting()) {
  60440. var alphaTexture = material.getAlphaTestTexture();
  60441. if (alphaTexture) {
  60442. defines.push("#define ALPHATEST");
  60443. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60444. attribs.push(BABYLON.VertexBuffer.UVKind);
  60445. defines.push("#define UV1");
  60446. }
  60447. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60448. if (alphaTexture.coordinatesIndex === 1) {
  60449. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60450. defines.push("#define UV2");
  60451. }
  60452. }
  60453. }
  60454. }
  60455. // Bones
  60456. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60457. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60458. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60459. if (mesh.numBoneInfluencers > 4) {
  60460. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60461. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60462. }
  60463. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60464. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  60465. }
  60466. else {
  60467. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60468. }
  60469. // Instances
  60470. if (useInstances) {
  60471. defines.push("#define INSTANCES");
  60472. attribs.push("world0");
  60473. attribs.push("world1");
  60474. attribs.push("world2");
  60475. attribs.push("world3");
  60476. }
  60477. // Get correct effect
  60478. var join = defines.join("\n");
  60479. if (this._cachedDefines !== join) {
  60480. this._cachedDefines = join;
  60481. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  60482. }
  60483. if (!this._effect.isReady()) {
  60484. return false;
  60485. }
  60486. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  60487. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  60488. this._initializeBlurRTTAndPostProcesses();
  60489. }
  60490. }
  60491. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  60492. return false;
  60493. }
  60494. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  60495. return false;
  60496. }
  60497. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  60498. return false;
  60499. }
  60500. return true;
  60501. };
  60502. /**
  60503. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  60504. * @param defines Defines of the material we want to update
  60505. * @param lightIndex Index of the light in the enabled light list of the material
  60506. */
  60507. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  60508. var scene = this._scene;
  60509. var light = this._light;
  60510. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  60511. return;
  60512. }
  60513. defines["SHADOW" + lightIndex] = true;
  60514. if (this.usePoissonSampling) {
  60515. defines["SHADOWPCF" + lightIndex] = true;
  60516. }
  60517. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  60518. defines["SHADOWESM" + lightIndex] = true;
  60519. }
  60520. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  60521. defines["SHADOWCLOSEESM" + lightIndex] = true;
  60522. }
  60523. if (light.needCube()) {
  60524. defines["SHADOWCUBE" + lightIndex] = true;
  60525. }
  60526. };
  60527. /**
  60528. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  60529. * defined in the generator but impacting the effect).
  60530. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  60531. * @param effect The effect we are binfing the information for
  60532. */
  60533. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  60534. var light = this._light;
  60535. var scene = this._scene;
  60536. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  60537. return;
  60538. }
  60539. var camera = scene.activeCamera;
  60540. if (!camera) {
  60541. return;
  60542. }
  60543. var shadowMap = this.getShadowMap();
  60544. if (!shadowMap) {
  60545. return;
  60546. }
  60547. if (!light.needCube()) {
  60548. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  60549. }
  60550. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  60551. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  60552. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  60553. };
  60554. /**
  60555. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  60556. * (eq to shadow prjection matrix * light transform matrix)
  60557. * @returns The transform matrix used to create the shadow map
  60558. */
  60559. ShadowGenerator.prototype.getTransformMatrix = function () {
  60560. var scene = this._scene;
  60561. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  60562. return this._transformMatrix;
  60563. }
  60564. this._currentRenderID = scene.getRenderId();
  60565. this._currentFaceIndexCache = this._currentFaceIndex;
  60566. var lightPosition = this._light.position;
  60567. if (this._light.computeTransformedInformation()) {
  60568. lightPosition = this._light.transformedPosition;
  60569. }
  60570. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  60571. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  60572. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  60573. }
  60574. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  60575. this._cachedPosition = lightPosition.clone();
  60576. this._cachedDirection = this._lightDirection.clone();
  60577. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  60578. var shadowMap = this.getShadowMap();
  60579. if (shadowMap) {
  60580. var renderList = shadowMap.renderList;
  60581. if (renderList) {
  60582. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  60583. }
  60584. }
  60585. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  60586. }
  60587. return this._transformMatrix;
  60588. };
  60589. /**
  60590. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  60591. * Cube and 2D textures for instance.
  60592. */
  60593. ShadowGenerator.prototype.recreateShadowMap = function () {
  60594. var shadowMap = this._shadowMap;
  60595. if (!shadowMap) {
  60596. return;
  60597. }
  60598. // Track render list.
  60599. var renderList = shadowMap.renderList;
  60600. // Clean up existing data.
  60601. this._disposeRTTandPostProcesses();
  60602. // Reinitializes.
  60603. this._initializeGenerator();
  60604. // Reaffect the filter to ensure a correct fallback if necessary.
  60605. this.filter = this.filter;
  60606. // Reaffect the filter.
  60607. this._applyFilterValues();
  60608. // Reaffect Render List.
  60609. this._shadowMap.renderList = renderList;
  60610. };
  60611. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  60612. if (this._shadowMap2) {
  60613. this._shadowMap2.dispose();
  60614. this._shadowMap2 = null;
  60615. }
  60616. if (this._boxBlurPostprocess) {
  60617. this._boxBlurPostprocess.dispose();
  60618. this._boxBlurPostprocess = null;
  60619. }
  60620. if (this._kernelBlurXPostprocess) {
  60621. this._kernelBlurXPostprocess.dispose();
  60622. this._kernelBlurXPostprocess = null;
  60623. }
  60624. if (this._kernelBlurYPostprocess) {
  60625. this._kernelBlurYPostprocess.dispose();
  60626. this._kernelBlurYPostprocess = null;
  60627. }
  60628. this._blurPostProcesses = [];
  60629. };
  60630. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  60631. if (this._shadowMap) {
  60632. this._shadowMap.dispose();
  60633. this._shadowMap = null;
  60634. }
  60635. this._disposeBlurPostProcesses();
  60636. };
  60637. /**
  60638. * Disposes the ShadowGenerator.
  60639. * Returns nothing.
  60640. */
  60641. ShadowGenerator.prototype.dispose = function () {
  60642. this._disposeRTTandPostProcesses();
  60643. if (this._light) {
  60644. this._light._shadowGenerator = null;
  60645. this._light._markMeshesAsLightDirty();
  60646. }
  60647. };
  60648. /**
  60649. * Serializes the shadow generator setup to a json object.
  60650. * @returns The serialized JSON object
  60651. */
  60652. ShadowGenerator.prototype.serialize = function () {
  60653. var serializationObject = {};
  60654. var shadowMap = this.getShadowMap();
  60655. if (!shadowMap) {
  60656. return serializationObject;
  60657. }
  60658. serializationObject.lightId = this._light.id;
  60659. serializationObject.mapSize = shadowMap.getRenderSize();
  60660. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  60661. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  60662. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  60663. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  60664. serializationObject.usePoissonSampling = this.usePoissonSampling;
  60665. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  60666. serializationObject.depthScale = this.depthScale;
  60667. serializationObject.darkness = this.getDarkness();
  60668. serializationObject.blurBoxOffset = this.blurBoxOffset;
  60669. serializationObject.blurKernel = this.blurKernel;
  60670. serializationObject.blurScale = this.blurScale;
  60671. serializationObject.useKernelBlur = this.useKernelBlur;
  60672. serializationObject.transparencyShadow = this._transparencyShadow;
  60673. serializationObject.renderList = [];
  60674. if (shadowMap.renderList) {
  60675. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  60676. var mesh = shadowMap.renderList[meshIndex];
  60677. serializationObject.renderList.push(mesh.id);
  60678. }
  60679. }
  60680. return serializationObject;
  60681. };
  60682. /**
  60683. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  60684. * @param parsedShadowGenerator The JSON object to parse
  60685. * @param scene The scene to create the shadow map for
  60686. * @returns The parsed shadow generator
  60687. */
  60688. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  60689. //casting to point light, as light is missing the position attr and typescript complains.
  60690. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  60691. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  60692. var shadowMap = shadowGenerator.getShadowMap();
  60693. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  60694. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  60695. meshes.forEach(function (mesh) {
  60696. if (!shadowMap) {
  60697. return;
  60698. }
  60699. if (!shadowMap.renderList) {
  60700. shadowMap.renderList = [];
  60701. }
  60702. shadowMap.renderList.push(mesh);
  60703. });
  60704. }
  60705. if (parsedShadowGenerator.usePoissonSampling) {
  60706. shadowGenerator.usePoissonSampling = true;
  60707. }
  60708. else if (parsedShadowGenerator.useExponentialShadowMap) {
  60709. shadowGenerator.useExponentialShadowMap = true;
  60710. }
  60711. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  60712. shadowGenerator.useBlurExponentialShadowMap = true;
  60713. }
  60714. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  60715. shadowGenerator.useCloseExponentialShadowMap = true;
  60716. }
  60717. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  60718. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  60719. }
  60720. else if (parsedShadowGenerator.useVarianceShadowMap) {
  60721. shadowGenerator.useExponentialShadowMap = true;
  60722. }
  60723. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  60724. shadowGenerator.useBlurExponentialShadowMap = true;
  60725. }
  60726. if (parsedShadowGenerator.depthScale) {
  60727. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  60728. }
  60729. if (parsedShadowGenerator.blurScale) {
  60730. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  60731. }
  60732. if (parsedShadowGenerator.blurBoxOffset) {
  60733. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  60734. }
  60735. if (parsedShadowGenerator.useKernelBlur) {
  60736. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  60737. }
  60738. if (parsedShadowGenerator.blurKernel) {
  60739. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  60740. }
  60741. if (parsedShadowGenerator.bias !== undefined) {
  60742. shadowGenerator.bias = parsedShadowGenerator.bias;
  60743. }
  60744. if (parsedShadowGenerator.darkness) {
  60745. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  60746. }
  60747. if (parsedShadowGenerator.transparencyShadow) {
  60748. shadowGenerator.setTransparencyShadow(true);
  60749. }
  60750. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  60751. return shadowGenerator;
  60752. };
  60753. ShadowGenerator._FILTER_NONE = 0;
  60754. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  60755. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  60756. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  60757. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  60758. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  60759. return ShadowGenerator;
  60760. }());
  60761. BABYLON.ShadowGenerator = ShadowGenerator;
  60762. })(BABYLON || (BABYLON = {}));
  60763. //# sourceMappingURL=babylon.shadowGenerator.js.map
  60764. var BABYLON;
  60765. (function (BABYLON) {
  60766. var DefaultLoadingScreen = /** @class */ (function () {
  60767. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  60768. if (_loadingText === void 0) { _loadingText = ""; }
  60769. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  60770. var _this = this;
  60771. this._renderingCanvas = _renderingCanvas;
  60772. this._loadingText = _loadingText;
  60773. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  60774. // Resize
  60775. this._resizeLoadingUI = function () {
  60776. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  60777. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  60778. if (!_this._loadingDiv) {
  60779. return;
  60780. }
  60781. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  60782. _this._loadingDiv.style.left = canvasRect.left + "px";
  60783. _this._loadingDiv.style.top = canvasRect.top + "px";
  60784. _this._loadingDiv.style.width = canvasRect.width + "px";
  60785. _this._loadingDiv.style.height = canvasRect.height + "px";
  60786. };
  60787. }
  60788. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  60789. if (this._loadingDiv) {
  60790. // Do not add a loading screen if there is already one
  60791. return;
  60792. }
  60793. this._loadingDiv = document.createElement("div");
  60794. this._loadingDiv.id = "babylonjsLoadingDiv";
  60795. this._loadingDiv.style.opacity = "0";
  60796. this._loadingDiv.style.transition = "opacity 1.5s ease";
  60797. this._loadingDiv.style.pointerEvents = "none";
  60798. // Loading text
  60799. this._loadingTextDiv = document.createElement("div");
  60800. this._loadingTextDiv.style.position = "absolute";
  60801. this._loadingTextDiv.style.left = "0";
  60802. this._loadingTextDiv.style.top = "50%";
  60803. this._loadingTextDiv.style.marginTop = "80px";
  60804. this._loadingTextDiv.style.width = "100%";
  60805. this._loadingTextDiv.style.height = "20px";
  60806. this._loadingTextDiv.style.fontFamily = "Arial";
  60807. this._loadingTextDiv.style.fontSize = "14px";
  60808. this._loadingTextDiv.style.color = "white";
  60809. this._loadingTextDiv.style.textAlign = "center";
  60810. this._loadingTextDiv.innerHTML = "Loading";
  60811. this._loadingDiv.appendChild(this._loadingTextDiv);
  60812. //set the predefined text
  60813. this._loadingTextDiv.innerHTML = this._loadingText;
  60814. // Generating keyframes
  60815. var style = document.createElement('style');
  60816. style.type = 'text/css';
  60817. 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 }";
  60818. style.innerHTML = keyFrames;
  60819. document.getElementsByTagName('head')[0].appendChild(style);
  60820. // Loading img
  60821. var imgBack = new Image();
  60822. 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";
  60823. imgBack.style.position = "absolute";
  60824. imgBack.style.left = "50%";
  60825. imgBack.style.top = "50%";
  60826. imgBack.style.marginLeft = "-60px";
  60827. imgBack.style.marginTop = "-60px";
  60828. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  60829. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  60830. imgBack.style.transformOrigin = "50% 50%";
  60831. imgBack.style.webkitTransformOrigin = "50% 50%";
  60832. this._loadingDiv.appendChild(imgBack);
  60833. this._resizeLoadingUI();
  60834. window.addEventListener("resize", this._resizeLoadingUI);
  60835. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  60836. document.body.appendChild(this._loadingDiv);
  60837. this._loadingDiv.style.opacity = "1";
  60838. };
  60839. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  60840. var _this = this;
  60841. if (!this._loadingDiv) {
  60842. return;
  60843. }
  60844. var onTransitionEnd = function () {
  60845. if (!_this._loadingDiv) {
  60846. return;
  60847. }
  60848. document.body.removeChild(_this._loadingDiv);
  60849. window.removeEventListener("resize", _this._resizeLoadingUI);
  60850. _this._loadingDiv = null;
  60851. };
  60852. this._loadingDiv.style.opacity = "0";
  60853. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  60854. };
  60855. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  60856. set: function (text) {
  60857. this._loadingText = text;
  60858. if (this._loadingTextDiv) {
  60859. this._loadingTextDiv.innerHTML = this._loadingText;
  60860. }
  60861. },
  60862. enumerable: true,
  60863. configurable: true
  60864. });
  60865. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  60866. get: function () {
  60867. return this._loadingDivBackgroundColor;
  60868. },
  60869. set: function (color) {
  60870. this._loadingDivBackgroundColor = color;
  60871. if (!this._loadingDiv) {
  60872. return;
  60873. }
  60874. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  60875. },
  60876. enumerable: true,
  60877. configurable: true
  60878. });
  60879. return DefaultLoadingScreen;
  60880. }());
  60881. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  60882. })(BABYLON || (BABYLON = {}));
  60883. //# sourceMappingURL=babylon.loadingScreen.js.map
  60884. var BABYLON;
  60885. (function (BABYLON) {
  60886. var SceneLoaderProgressEvent = /** @class */ (function () {
  60887. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  60888. this.lengthComputable = lengthComputable;
  60889. this.loaded = loaded;
  60890. this.total = total;
  60891. }
  60892. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  60893. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  60894. };
  60895. return SceneLoaderProgressEvent;
  60896. }());
  60897. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  60898. var SceneLoader = /** @class */ (function () {
  60899. function SceneLoader() {
  60900. }
  60901. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  60902. get: function () {
  60903. return 0;
  60904. },
  60905. enumerable: true,
  60906. configurable: true
  60907. });
  60908. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  60909. get: function () {
  60910. return 1;
  60911. },
  60912. enumerable: true,
  60913. configurable: true
  60914. });
  60915. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  60916. get: function () {
  60917. return 2;
  60918. },
  60919. enumerable: true,
  60920. configurable: true
  60921. });
  60922. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  60923. get: function () {
  60924. return 3;
  60925. },
  60926. enumerable: true,
  60927. configurable: true
  60928. });
  60929. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  60930. get: function () {
  60931. return SceneLoader._ForceFullSceneLoadingForIncremental;
  60932. },
  60933. set: function (value) {
  60934. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  60935. },
  60936. enumerable: true,
  60937. configurable: true
  60938. });
  60939. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  60940. get: function () {
  60941. return SceneLoader._ShowLoadingScreen;
  60942. },
  60943. set: function (value) {
  60944. SceneLoader._ShowLoadingScreen = value;
  60945. },
  60946. enumerable: true,
  60947. configurable: true
  60948. });
  60949. Object.defineProperty(SceneLoader, "loggingLevel", {
  60950. get: function () {
  60951. return SceneLoader._loggingLevel;
  60952. },
  60953. set: function (value) {
  60954. SceneLoader._loggingLevel = value;
  60955. },
  60956. enumerable: true,
  60957. configurable: true
  60958. });
  60959. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  60960. get: function () {
  60961. return SceneLoader._CleanBoneMatrixWeights;
  60962. },
  60963. set: function (value) {
  60964. SceneLoader._CleanBoneMatrixWeights = value;
  60965. },
  60966. enumerable: true,
  60967. configurable: true
  60968. });
  60969. SceneLoader._getDefaultPlugin = function () {
  60970. return SceneLoader._registeredPlugins[".babylon"];
  60971. };
  60972. SceneLoader._getPluginForExtension = function (extension) {
  60973. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  60974. if (registeredPlugin) {
  60975. return registeredPlugin;
  60976. }
  60977. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  60978. return SceneLoader._getDefaultPlugin();
  60979. };
  60980. SceneLoader._getPluginForDirectLoad = function (data) {
  60981. for (var extension in SceneLoader._registeredPlugins) {
  60982. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  60983. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  60984. return SceneLoader._registeredPlugins[extension];
  60985. }
  60986. }
  60987. return SceneLoader._getDefaultPlugin();
  60988. };
  60989. SceneLoader._getPluginForFilename = function (sceneFilename) {
  60990. if (sceneFilename.name) {
  60991. sceneFilename = sceneFilename.name;
  60992. }
  60993. var queryStringPosition = sceneFilename.indexOf("?");
  60994. if (queryStringPosition !== -1) {
  60995. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  60996. }
  60997. var dotPosition = sceneFilename.lastIndexOf(".");
  60998. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  60999. return SceneLoader._getPluginForExtension(extension);
  61000. };
  61001. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  61002. SceneLoader._getDirectLoad = function (sceneFilename) {
  61003. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  61004. return sceneFilename.substr(5);
  61005. }
  61006. return null;
  61007. };
  61008. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  61009. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  61010. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  61011. var plugin;
  61012. if (registeredPlugin.plugin.createPlugin) {
  61013. plugin = registeredPlugin.plugin.createPlugin();
  61014. }
  61015. else {
  61016. plugin = registeredPlugin.plugin;
  61017. }
  61018. var useArrayBuffer = registeredPlugin.isBinary;
  61019. var database;
  61020. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  61021. var dataCallback = function (data, responseURL) {
  61022. if (scene.isDisposed) {
  61023. onError("Scene has been disposed");
  61024. return;
  61025. }
  61026. scene.database = database;
  61027. onSuccess(plugin, data, responseURL);
  61028. };
  61029. var request = null;
  61030. var pluginDisposed = false;
  61031. var onDisposeObservable = plugin.onDisposeObservable;
  61032. if (onDisposeObservable) {
  61033. onDisposeObservable.add(function () {
  61034. pluginDisposed = true;
  61035. if (request) {
  61036. request.abort();
  61037. request = null;
  61038. }
  61039. onDispose();
  61040. });
  61041. }
  61042. var manifestChecked = function () {
  61043. if (pluginDisposed) {
  61044. return;
  61045. }
  61046. var url = rootUrl + sceneFilename;
  61047. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  61048. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  61049. } : undefined, database, useArrayBuffer, function (request, exception) {
  61050. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  61051. });
  61052. };
  61053. if (directLoad) {
  61054. dataCallback(directLoad);
  61055. return plugin;
  61056. }
  61057. if (rootUrl.indexOf("file:") === -1) {
  61058. if (scene.getEngine().enableOfflineSupport) {
  61059. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  61060. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  61061. }
  61062. else {
  61063. manifestChecked();
  61064. }
  61065. }
  61066. else {
  61067. var fileOrString = sceneFilename;
  61068. if (fileOrString.name) {
  61069. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  61070. }
  61071. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  61072. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  61073. }
  61074. else {
  61075. onError("Unable to find file named " + sceneFilename);
  61076. }
  61077. }
  61078. return plugin;
  61079. };
  61080. // Public functions
  61081. SceneLoader.GetPluginForExtension = function (extension) {
  61082. return SceneLoader._getPluginForExtension(extension).plugin;
  61083. };
  61084. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  61085. return !!SceneLoader._registeredPlugins[extension];
  61086. };
  61087. SceneLoader.RegisterPlugin = function (plugin) {
  61088. if (typeof plugin.extensions === "string") {
  61089. var extension = plugin.extensions;
  61090. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  61091. plugin: plugin,
  61092. isBinary: false
  61093. };
  61094. }
  61095. else {
  61096. var extensions = plugin.extensions;
  61097. Object.keys(extensions).forEach(function (extension) {
  61098. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  61099. plugin: plugin,
  61100. isBinary: extensions[extension].isBinary
  61101. };
  61102. });
  61103. }
  61104. };
  61105. /**
  61106. * Import meshes into a scene
  61107. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  61108. * @param rootUrl a string that defines the root url for scene and resources
  61109. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61110. * @param scene the instance of BABYLON.Scene to append to
  61111. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  61112. * @param onProgress a callback with a progress event for each file being loaded
  61113. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61114. * @param pluginExtension the extension used to determine the plugin
  61115. * @returns The loaded plugin
  61116. */
  61117. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61118. if (onSuccess === void 0) { onSuccess = null; }
  61119. if (onProgress === void 0) { onProgress = null; }
  61120. if (onError === void 0) { onError = null; }
  61121. if (pluginExtension === void 0) { pluginExtension = null; }
  61122. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61123. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61124. return null;
  61125. }
  61126. var loadingToken = {};
  61127. scene._addPendingData(loadingToken);
  61128. var disposeHandler = function () {
  61129. scene._removePendingData(loadingToken);
  61130. };
  61131. var errorHandler = function (message, exception) {
  61132. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  61133. if (onError) {
  61134. onError(scene, errorMessage, exception);
  61135. }
  61136. else {
  61137. BABYLON.Tools.Error(errorMessage);
  61138. // should the exception be thrown?
  61139. }
  61140. disposeHandler();
  61141. };
  61142. var progressHandler = onProgress ? function (event) {
  61143. try {
  61144. onProgress(event);
  61145. }
  61146. catch (e) {
  61147. errorHandler("Error in onProgress callback", e);
  61148. }
  61149. } : undefined;
  61150. var successHandler = function (meshes, particleSystems, skeletons) {
  61151. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  61152. if (onSuccess) {
  61153. try {
  61154. onSuccess(meshes, particleSystems, skeletons);
  61155. }
  61156. catch (e) {
  61157. errorHandler("Error in onSuccess callback", e);
  61158. }
  61159. }
  61160. scene._removePendingData(loadingToken);
  61161. };
  61162. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61163. if (plugin.rewriteRootURL) {
  61164. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  61165. }
  61166. if (sceneFilename === "") {
  61167. if (sceneFilename === "") {
  61168. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  61169. }
  61170. }
  61171. if (plugin.importMesh) {
  61172. var syncedPlugin = plugin;
  61173. var meshes = new Array();
  61174. var particleSystems = new Array();
  61175. var skeletons = new Array();
  61176. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  61177. return;
  61178. }
  61179. scene.loadingPluginName = plugin.name;
  61180. successHandler(meshes, particleSystems, skeletons);
  61181. }
  61182. else {
  61183. var asyncedPlugin = plugin;
  61184. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  61185. scene.loadingPluginName = plugin.name;
  61186. successHandler(result.meshes, result.particleSystems, result.skeletons);
  61187. }).catch(function (error) {
  61188. errorHandler(error.message, error);
  61189. });
  61190. }
  61191. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61192. };
  61193. /**
  61194. * Import meshes into a scene
  61195. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  61196. * @param rootUrl a string that defines the root url for scene and resources
  61197. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61198. * @param scene the instance of BABYLON.Scene to append to
  61199. * @param onProgress a callback with a progress event for each file being loaded
  61200. * @param pluginExtension the extension used to determine the plugin
  61201. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  61202. */
  61203. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61204. if (onProgress === void 0) { onProgress = null; }
  61205. if (pluginExtension === void 0) { pluginExtension = null; }
  61206. return new Promise(function (resolve, reject) {
  61207. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  61208. resolve({
  61209. meshes: meshes,
  61210. particleSystems: particleSystems,
  61211. skeletons: skeletons
  61212. });
  61213. }, onProgress, function (scene, message, exception) {
  61214. reject(exception || new Error(message));
  61215. });
  61216. });
  61217. };
  61218. /**
  61219. * Load a scene
  61220. * @param rootUrl a string that defines the root url for scene and resources
  61221. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61222. * @param engine is the instance of BABYLON.Engine to use to create the scene
  61223. * @param onSuccess a callback with the scene when import succeeds
  61224. * @param onProgress a callback with a progress event for each file being loaded
  61225. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61226. * @param pluginExtension the extension used to determine the plugin
  61227. * @returns The loaded plugin
  61228. */
  61229. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  61230. if (onSuccess === void 0) { onSuccess = null; }
  61231. if (onProgress === void 0) { onProgress = null; }
  61232. if (onError === void 0) { onError = null; }
  61233. if (pluginExtension === void 0) { pluginExtension = null; }
  61234. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  61235. };
  61236. /**
  61237. * Load a scene
  61238. * @param rootUrl a string that defines the root url for scene and resources
  61239. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61240. * @param engine is the instance of BABYLON.Engine to use to create the scene
  61241. * @param onProgress a callback with a progress event for each file being loaded
  61242. * @param pluginExtension the extension used to determine the plugin
  61243. * @returns The loaded scene
  61244. */
  61245. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  61246. if (onProgress === void 0) { onProgress = null; }
  61247. if (pluginExtension === void 0) { pluginExtension = null; }
  61248. return new Promise(function (resolve, reject) {
  61249. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  61250. resolve(scene);
  61251. }, onProgress, function (scene, message, exception) {
  61252. reject(exception || new Error(message));
  61253. }, pluginExtension);
  61254. });
  61255. };
  61256. /**
  61257. * Append a scene
  61258. * @param rootUrl a string that defines the root url for scene and resources
  61259. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61260. * @param scene is the instance of BABYLON.Scene to append to
  61261. * @param onSuccess a callback with the scene when import succeeds
  61262. * @param onProgress a callback with a progress event for each file being loaded
  61263. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61264. * @param pluginExtension the extension used to determine the plugin
  61265. * @returns The loaded plugin
  61266. */
  61267. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61268. if (onSuccess === void 0) { onSuccess = null; }
  61269. if (onProgress === void 0) { onProgress = null; }
  61270. if (onError === void 0) { onError = null; }
  61271. if (pluginExtension === void 0) { pluginExtension = null; }
  61272. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61273. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61274. return null;
  61275. }
  61276. if (SceneLoader.ShowLoadingScreen) {
  61277. scene.getEngine().displayLoadingUI();
  61278. }
  61279. var loadingToken = {};
  61280. scene._addPendingData(loadingToken);
  61281. var disposeHandler = function () {
  61282. scene._removePendingData(loadingToken);
  61283. scene.getEngine().hideLoadingUI();
  61284. };
  61285. var errorHandler = function (message, exception) {
  61286. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  61287. if (onError) {
  61288. onError(scene, errorMessage, exception);
  61289. }
  61290. else {
  61291. BABYLON.Tools.Error(errorMessage);
  61292. // should the exception be thrown?
  61293. }
  61294. disposeHandler();
  61295. };
  61296. var progressHandler = onProgress ? function (event) {
  61297. try {
  61298. onProgress(event);
  61299. }
  61300. catch (e) {
  61301. errorHandler("Error in onProgress callback", e);
  61302. }
  61303. } : undefined;
  61304. var successHandler = function () {
  61305. if (onSuccess) {
  61306. try {
  61307. onSuccess(scene);
  61308. }
  61309. catch (e) {
  61310. errorHandler("Error in onSuccess callback", e);
  61311. }
  61312. }
  61313. scene._removePendingData(loadingToken);
  61314. };
  61315. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61316. if (sceneFilename === "") {
  61317. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  61318. }
  61319. if (plugin.load) {
  61320. var syncedPlugin = plugin;
  61321. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  61322. return;
  61323. }
  61324. scene.loadingPluginName = plugin.name;
  61325. successHandler();
  61326. }
  61327. else {
  61328. var asyncedPlugin = plugin;
  61329. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  61330. scene.loadingPluginName = plugin.name;
  61331. successHandler();
  61332. }).catch(function (error) {
  61333. errorHandler(error.message, error);
  61334. });
  61335. }
  61336. if (SceneLoader.ShowLoadingScreen) {
  61337. scene.executeWhenReady(function () {
  61338. scene.getEngine().hideLoadingUI();
  61339. });
  61340. }
  61341. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61342. };
  61343. /**
  61344. * Append a scene
  61345. * @param rootUrl a string that defines the root url for scene and resources
  61346. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61347. * @param scene is the instance of BABYLON.Scene to append to
  61348. * @param onProgress a callback with a progress event for each file being loaded
  61349. * @param pluginExtension the extension used to determine the plugin
  61350. * @returns The given scene
  61351. */
  61352. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61353. if (onProgress === void 0) { onProgress = null; }
  61354. if (pluginExtension === void 0) { pluginExtension = null; }
  61355. return new Promise(function (resolve, reject) {
  61356. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  61357. resolve(scene);
  61358. }, onProgress, function (scene, message, exception) {
  61359. reject(exception || new Error(message));
  61360. }, pluginExtension);
  61361. });
  61362. };
  61363. /**
  61364. * Load a scene into an asset container
  61365. * @param rootUrl a string that defines the root url for scene and resources
  61366. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61367. * @param scene is the instance of BABYLON.Scene to append to
  61368. * @param onSuccess a callback with the scene when import succeeds
  61369. * @param onProgress a callback with a progress event for each file being loaded
  61370. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61371. * @param pluginExtension the extension used to determine the plugin
  61372. * @returns The loaded plugin
  61373. */
  61374. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61375. if (onSuccess === void 0) { onSuccess = null; }
  61376. if (onProgress === void 0) { onProgress = null; }
  61377. if (onError === void 0) { onError = null; }
  61378. if (pluginExtension === void 0) { pluginExtension = null; }
  61379. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61380. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61381. return null;
  61382. }
  61383. var loadingToken = {};
  61384. scene._addPendingData(loadingToken);
  61385. var disposeHandler = function () {
  61386. scene._removePendingData(loadingToken);
  61387. };
  61388. var errorHandler = function (message, exception) {
  61389. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  61390. if (onError) {
  61391. onError(scene, errorMessage, exception);
  61392. }
  61393. else {
  61394. BABYLON.Tools.Error(errorMessage);
  61395. // should the exception be thrown?
  61396. }
  61397. disposeHandler();
  61398. };
  61399. var progressHandler = onProgress ? function (event) {
  61400. try {
  61401. onProgress(event);
  61402. }
  61403. catch (e) {
  61404. errorHandler("Error in onProgress callback", e);
  61405. }
  61406. } : undefined;
  61407. var successHandler = function (assets) {
  61408. if (onSuccess) {
  61409. try {
  61410. onSuccess(assets);
  61411. }
  61412. catch (e) {
  61413. errorHandler("Error in onSuccess callback", e);
  61414. }
  61415. }
  61416. scene._removePendingData(loadingToken);
  61417. };
  61418. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61419. if (plugin.loadAssetContainer) {
  61420. var syncedPlugin = plugin;
  61421. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  61422. if (!assetContainer) {
  61423. return;
  61424. }
  61425. scene.loadingPluginName = plugin.name;
  61426. successHandler(assetContainer);
  61427. }
  61428. else if (plugin.loadAssetContainerAsync) {
  61429. var asyncedPlugin = plugin;
  61430. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  61431. scene.loadingPluginName = plugin.name;
  61432. successHandler(assetContainer);
  61433. }).catch(function (error) {
  61434. errorHandler(error.message, error);
  61435. });
  61436. }
  61437. else {
  61438. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  61439. }
  61440. if (SceneLoader.ShowLoadingScreen) {
  61441. scene.executeWhenReady(function () {
  61442. scene.getEngine().hideLoadingUI();
  61443. });
  61444. }
  61445. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61446. };
  61447. /**
  61448. * Load a scene into an asset container
  61449. * @param rootUrl a string that defines the root url for scene and resources
  61450. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61451. * @param scene is the instance of BABYLON.Scene to append to
  61452. * @param onProgress a callback with a progress event for each file being loaded
  61453. * @param pluginExtension the extension used to determine the plugin
  61454. * @returns The loaded asset container
  61455. */
  61456. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61457. if (onProgress === void 0) { onProgress = null; }
  61458. if (pluginExtension === void 0) { pluginExtension = null; }
  61459. return new Promise(function (resolve, reject) {
  61460. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  61461. resolve(assetContainer);
  61462. }, onProgress, function (scene, message, exception) {
  61463. reject(exception || new Error(message));
  61464. }, pluginExtension);
  61465. });
  61466. };
  61467. // Flags
  61468. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  61469. SceneLoader._ShowLoadingScreen = true;
  61470. SceneLoader._CleanBoneMatrixWeights = false;
  61471. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  61472. // Members
  61473. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  61474. SceneLoader._registeredPlugins = {};
  61475. return SceneLoader;
  61476. }());
  61477. BABYLON.SceneLoader = SceneLoader;
  61478. ;
  61479. })(BABYLON || (BABYLON = {}));
  61480. //# sourceMappingURL=babylon.sceneLoader.js.map
  61481. var BABYLON;
  61482. (function (BABYLON) {
  61483. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  61484. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  61485. var parsedMaterial = parsedData.materials[index];
  61486. if (parsedMaterial.id === id) {
  61487. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  61488. }
  61489. }
  61490. return null;
  61491. };
  61492. var isDescendantOf = function (mesh, names, hierarchyIds) {
  61493. for (var i in names) {
  61494. if (mesh.name === names[i]) {
  61495. hierarchyIds.push(mesh.id);
  61496. return true;
  61497. }
  61498. }
  61499. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  61500. hierarchyIds.push(mesh.id);
  61501. return true;
  61502. }
  61503. return false;
  61504. };
  61505. var logOperation = function (operation, producer) {
  61506. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  61507. };
  61508. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  61509. if (addToScene === void 0) { addToScene = false; }
  61510. var container = new BABYLON.AssetContainer(scene);
  61511. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61512. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61513. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61514. // and avoid problems with multiple concurrent .babylon loads.
  61515. var log = "importScene has failed JSON parse";
  61516. try {
  61517. var parsedData = JSON.parse(data);
  61518. log = "";
  61519. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  61520. var index;
  61521. var cache;
  61522. // Lights
  61523. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  61524. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  61525. var parsedLight = parsedData.lights[index];
  61526. var light = BABYLON.Light.Parse(parsedLight, scene);
  61527. if (light) {
  61528. container.lights.push(light);
  61529. log += (index === 0 ? "\n\tLights:" : "");
  61530. log += "\n\t\t" + light.toString(fullDetails);
  61531. }
  61532. }
  61533. }
  61534. // Animations
  61535. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  61536. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  61537. var parsedAnimation = parsedData.animations[index];
  61538. var animation = BABYLON.Animation.Parse(parsedAnimation);
  61539. scene.animations.push(animation);
  61540. container.animations.push(animation);
  61541. log += (index === 0 ? "\n\tAnimations:" : "");
  61542. log += "\n\t\t" + animation.toString(fullDetails);
  61543. }
  61544. }
  61545. // Materials
  61546. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  61547. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  61548. var parsedMaterial = parsedData.materials[index];
  61549. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  61550. container.materials.push(mat);
  61551. log += (index === 0 ? "\n\tMaterials:" : "");
  61552. log += "\n\t\t" + mat.toString(fullDetails);
  61553. }
  61554. }
  61555. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  61556. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  61557. var parsedMultiMaterial = parsedData.multiMaterials[index];
  61558. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  61559. container.multiMaterials.push(mmat);
  61560. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  61561. log += "\n\t\t" + mmat.toString(fullDetails);
  61562. }
  61563. }
  61564. // Morph targets
  61565. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  61566. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  61567. var managerData = _a[_i];
  61568. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  61569. }
  61570. }
  61571. // Skeletons
  61572. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  61573. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  61574. var parsedSkeleton = parsedData.skeletons[index];
  61575. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  61576. container.skeletons.push(skeleton);
  61577. log += (index === 0 ? "\n\tSkeletons:" : "");
  61578. log += "\n\t\t" + skeleton.toString(fullDetails);
  61579. }
  61580. }
  61581. // Geometries
  61582. var geometries = parsedData.geometries;
  61583. if (geometries !== undefined && geometries !== null) {
  61584. var addedGeometry = new Array();
  61585. // Boxes
  61586. var boxes = geometries.boxes;
  61587. if (boxes !== undefined && boxes !== null) {
  61588. for (index = 0, cache = boxes.length; index < cache; index++) {
  61589. var parsedBox = boxes[index];
  61590. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  61591. }
  61592. }
  61593. // Spheres
  61594. var spheres = geometries.spheres;
  61595. if (spheres !== undefined && spheres !== null) {
  61596. for (index = 0, cache = spheres.length; index < cache; index++) {
  61597. var parsedSphere = spheres[index];
  61598. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  61599. }
  61600. }
  61601. // Cylinders
  61602. var cylinders = geometries.cylinders;
  61603. if (cylinders !== undefined && cylinders !== null) {
  61604. for (index = 0, cache = cylinders.length; index < cache; index++) {
  61605. var parsedCylinder = cylinders[index];
  61606. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  61607. }
  61608. }
  61609. // Toruses
  61610. var toruses = geometries.toruses;
  61611. if (toruses !== undefined && toruses !== null) {
  61612. for (index = 0, cache = toruses.length; index < cache; index++) {
  61613. var parsedTorus = toruses[index];
  61614. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  61615. }
  61616. }
  61617. // Grounds
  61618. var grounds = geometries.grounds;
  61619. if (grounds !== undefined && grounds !== null) {
  61620. for (index = 0, cache = grounds.length; index < cache; index++) {
  61621. var parsedGround = grounds[index];
  61622. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  61623. }
  61624. }
  61625. // Planes
  61626. var planes = geometries.planes;
  61627. if (planes !== undefined && planes !== null) {
  61628. for (index = 0, cache = planes.length; index < cache; index++) {
  61629. var parsedPlane = planes[index];
  61630. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  61631. }
  61632. }
  61633. // TorusKnots
  61634. var torusKnots = geometries.torusKnots;
  61635. if (torusKnots !== undefined && torusKnots !== null) {
  61636. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  61637. var parsedTorusKnot = torusKnots[index];
  61638. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  61639. }
  61640. }
  61641. // VertexData
  61642. var vertexData = geometries.vertexData;
  61643. if (vertexData !== undefined && vertexData !== null) {
  61644. for (index = 0, cache = vertexData.length; index < cache; index++) {
  61645. var parsedVertexData = vertexData[index];
  61646. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  61647. }
  61648. }
  61649. addedGeometry.forEach(function (g) {
  61650. if (g) {
  61651. container.geometries.push(g);
  61652. }
  61653. });
  61654. }
  61655. // Transform nodes
  61656. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  61657. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  61658. var parsedTransformNode = parsedData.transformNodes[index];
  61659. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  61660. container.transformNodes.push(node);
  61661. }
  61662. }
  61663. // Meshes
  61664. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  61665. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  61666. var parsedMesh = parsedData.meshes[index];
  61667. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  61668. container.meshes.push(mesh);
  61669. log += (index === 0 ? "\n\tMeshes:" : "");
  61670. log += "\n\t\t" + mesh.toString(fullDetails);
  61671. }
  61672. }
  61673. // Cameras
  61674. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  61675. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  61676. var parsedCamera = parsedData.cameras[index];
  61677. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  61678. container.cameras.push(camera);
  61679. log += (index === 0 ? "\n\tCameras:" : "");
  61680. log += "\n\t\t" + camera.toString(fullDetails);
  61681. }
  61682. }
  61683. // Browsing all the graph to connect the dots
  61684. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  61685. var camera = scene.cameras[index];
  61686. if (camera._waitingParentId) {
  61687. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  61688. camera._waitingParentId = null;
  61689. }
  61690. }
  61691. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  61692. var light_1 = scene.lights[index];
  61693. if (light_1 && light_1._waitingParentId) {
  61694. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  61695. light_1._waitingParentId = null;
  61696. }
  61697. }
  61698. // Sounds
  61699. // TODO: add sound
  61700. var loadedSounds = [];
  61701. var loadedSound;
  61702. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  61703. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  61704. var parsedSound = parsedData.sounds[index];
  61705. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61706. if (!parsedSound.url)
  61707. parsedSound.url = parsedSound.name;
  61708. if (!loadedSounds[parsedSound.url]) {
  61709. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  61710. loadedSounds[parsedSound.url] = loadedSound;
  61711. container.sounds.push(loadedSound);
  61712. }
  61713. else {
  61714. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  61715. }
  61716. }
  61717. else {
  61718. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  61719. }
  61720. }
  61721. }
  61722. loadedSounds = [];
  61723. // Connect parents & children and parse actions
  61724. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  61725. var transformNode = scene.transformNodes[index];
  61726. if (transformNode._waitingParentId) {
  61727. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  61728. transformNode._waitingParentId = null;
  61729. }
  61730. }
  61731. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61732. var mesh = scene.meshes[index];
  61733. if (mesh._waitingParentId) {
  61734. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  61735. mesh._waitingParentId = null;
  61736. }
  61737. if (mesh._waitingActions) {
  61738. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  61739. mesh._waitingActions = null;
  61740. }
  61741. }
  61742. // freeze world matrix application
  61743. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61744. var currentMesh = scene.meshes[index];
  61745. if (currentMesh._waitingFreezeWorldMatrix) {
  61746. currentMesh.freezeWorldMatrix();
  61747. currentMesh._waitingFreezeWorldMatrix = null;
  61748. }
  61749. else {
  61750. currentMesh.computeWorldMatrix(true);
  61751. }
  61752. }
  61753. // Particles Systems
  61754. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  61755. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  61756. var parsedParticleSystem = parsedData.particleSystems[index];
  61757. if (parsedParticleSystem.activeParticleCount) {
  61758. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61759. container.particleSystems.push(ps);
  61760. }
  61761. else {
  61762. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61763. container.particleSystems.push(ps);
  61764. }
  61765. }
  61766. }
  61767. // Lens flares
  61768. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  61769. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  61770. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  61771. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  61772. container.lensFlareSystems.push(lf);
  61773. }
  61774. }
  61775. // Shadows
  61776. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  61777. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  61778. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  61779. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  61780. container.shadowGenerators.push(sg);
  61781. }
  61782. }
  61783. // Lights exclusions / inclusions
  61784. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  61785. var light_2 = scene.lights[index];
  61786. // Excluded check
  61787. if (light_2._excludedMeshesIds.length > 0) {
  61788. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  61789. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  61790. if (excludedMesh) {
  61791. light_2.excludedMeshes.push(excludedMesh);
  61792. }
  61793. }
  61794. light_2._excludedMeshesIds = [];
  61795. }
  61796. // Included check
  61797. if (light_2._includedOnlyMeshesIds.length > 0) {
  61798. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  61799. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  61800. if (includedOnlyMesh) {
  61801. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  61802. }
  61803. }
  61804. light_2._includedOnlyMeshesIds = [];
  61805. }
  61806. }
  61807. // Actions (scene)
  61808. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  61809. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  61810. }
  61811. if (!addToScene) {
  61812. container.removeAllFromScene();
  61813. }
  61814. }
  61815. catch (err) {
  61816. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  61817. if (onError) {
  61818. onError(msg, err);
  61819. }
  61820. else {
  61821. BABYLON.Tools.Log(msg);
  61822. throw err;
  61823. }
  61824. }
  61825. finally {
  61826. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61827. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61828. }
  61829. }
  61830. return container;
  61831. };
  61832. BABYLON.SceneLoader.RegisterPlugin({
  61833. name: "babylon.js",
  61834. extensions: ".babylon",
  61835. canDirectLoad: function (data) {
  61836. if (data.indexOf("babylon") !== -1) {
  61837. return true;
  61838. }
  61839. return false;
  61840. },
  61841. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  61842. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61843. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61844. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61845. // and avoid problems with multiple concurrent .babylon loads.
  61846. var log = "importMesh has failed JSON parse";
  61847. try {
  61848. var parsedData = JSON.parse(data);
  61849. log = "";
  61850. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  61851. if (!meshesNames) {
  61852. meshesNames = null;
  61853. }
  61854. else if (!Array.isArray(meshesNames)) {
  61855. meshesNames = [meshesNames];
  61856. }
  61857. var hierarchyIds = new Array();
  61858. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  61859. var loadedSkeletonsIds = [];
  61860. var loadedMaterialsIds = [];
  61861. var index;
  61862. var cache;
  61863. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  61864. var parsedMesh = parsedData.meshes[index];
  61865. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  61866. if (meshesNames !== null) {
  61867. // Remove found mesh name from list.
  61868. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  61869. }
  61870. //Geometry?
  61871. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  61872. //does the file contain geometries?
  61873. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  61874. //find the correct geometry and add it to the scene
  61875. var found = false;
  61876. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  61877. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  61878. return;
  61879. }
  61880. else {
  61881. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  61882. if (parsedGeometryData.id === parsedMesh.geometryId) {
  61883. switch (geometryType) {
  61884. case "boxes":
  61885. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  61886. break;
  61887. case "spheres":
  61888. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  61889. break;
  61890. case "cylinders":
  61891. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  61892. break;
  61893. case "toruses":
  61894. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  61895. break;
  61896. case "grounds":
  61897. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  61898. break;
  61899. case "planes":
  61900. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  61901. break;
  61902. case "torusKnots":
  61903. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  61904. break;
  61905. case "vertexData":
  61906. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  61907. break;
  61908. }
  61909. found = true;
  61910. }
  61911. });
  61912. }
  61913. });
  61914. if (found === false) {
  61915. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  61916. }
  61917. }
  61918. }
  61919. // Material ?
  61920. if (parsedMesh.materialId) {
  61921. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  61922. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  61923. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  61924. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  61925. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  61926. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  61927. var subMatId = parsedMultiMaterial.materials[matIndex];
  61928. loadedMaterialsIds.push(subMatId);
  61929. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  61930. if (mat) {
  61931. log += "\n\tMaterial " + mat.toString(fullDetails);
  61932. }
  61933. }
  61934. loadedMaterialsIds.push(parsedMultiMaterial.id);
  61935. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  61936. if (mmat) {
  61937. materialFound = true;
  61938. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  61939. }
  61940. break;
  61941. }
  61942. }
  61943. }
  61944. if (materialFound === false) {
  61945. loadedMaterialsIds.push(parsedMesh.materialId);
  61946. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  61947. if (!mat) {
  61948. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  61949. }
  61950. else {
  61951. log += "\n\tMaterial " + mat.toString(fullDetails);
  61952. }
  61953. }
  61954. }
  61955. // Skeleton ?
  61956. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  61957. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  61958. if (skeletonAlreadyLoaded === false) {
  61959. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  61960. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  61961. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  61962. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  61963. skeletons.push(skeleton);
  61964. loadedSkeletonsIds.push(parsedSkeleton.id);
  61965. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  61966. }
  61967. }
  61968. }
  61969. }
  61970. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  61971. meshes.push(mesh);
  61972. log += "\n\tMesh " + mesh.toString(fullDetails);
  61973. }
  61974. }
  61975. // Connecting parents
  61976. var currentMesh;
  61977. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61978. currentMesh = scene.meshes[index];
  61979. if (currentMesh._waitingParentId) {
  61980. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  61981. currentMesh._waitingParentId = null;
  61982. }
  61983. }
  61984. // freeze and compute world matrix application
  61985. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61986. currentMesh = scene.meshes[index];
  61987. if (currentMesh._waitingFreezeWorldMatrix) {
  61988. currentMesh.freezeWorldMatrix();
  61989. currentMesh._waitingFreezeWorldMatrix = null;
  61990. }
  61991. else {
  61992. currentMesh.computeWorldMatrix(true);
  61993. }
  61994. }
  61995. }
  61996. // Particles
  61997. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  61998. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  61999. var parsedParticleSystem = parsedData.particleSystems[index];
  62000. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  62001. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  62002. }
  62003. }
  62004. }
  62005. return true;
  62006. }
  62007. catch (err) {
  62008. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  62009. if (onError) {
  62010. onError(msg, err);
  62011. }
  62012. else {
  62013. BABYLON.Tools.Log(msg);
  62014. throw err;
  62015. }
  62016. }
  62017. finally {
  62018. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62019. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62020. }
  62021. }
  62022. return false;
  62023. },
  62024. load: function (scene, data, rootUrl, onError) {
  62025. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62026. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62027. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62028. // and avoid problems with multiple concurrent .babylon loads.
  62029. var log = "importScene has failed JSON parse";
  62030. try {
  62031. var parsedData = JSON.parse(data);
  62032. log = "";
  62033. // Scene
  62034. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  62035. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  62036. }
  62037. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  62038. scene.autoClear = parsedData.autoClear;
  62039. }
  62040. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  62041. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  62042. }
  62043. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  62044. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  62045. }
  62046. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  62047. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  62048. }
  62049. // Fog
  62050. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  62051. scene.fogMode = parsedData.fogMode;
  62052. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  62053. scene.fogStart = parsedData.fogStart;
  62054. scene.fogEnd = parsedData.fogEnd;
  62055. scene.fogDensity = parsedData.fogDensity;
  62056. log += "\tFog mode for scene: ";
  62057. switch (scene.fogMode) {
  62058. // getters not compiling, so using hardcoded
  62059. case 1:
  62060. log += "exp\n";
  62061. break;
  62062. case 2:
  62063. log += "exp2\n";
  62064. break;
  62065. case 3:
  62066. log += "linear\n";
  62067. break;
  62068. }
  62069. }
  62070. //Physics
  62071. if (parsedData.physicsEnabled) {
  62072. var physicsPlugin;
  62073. if (parsedData.physicsEngine === "cannon") {
  62074. physicsPlugin = new BABYLON.CannonJSPlugin();
  62075. }
  62076. else if (parsedData.physicsEngine === "oimo") {
  62077. physicsPlugin = new BABYLON.OimoJSPlugin();
  62078. }
  62079. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  62080. //else - default engine, which is currently oimo
  62081. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  62082. scene.enablePhysics(physicsGravity, physicsPlugin);
  62083. }
  62084. // Metadata
  62085. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  62086. scene.metadata = parsedData.metadata;
  62087. }
  62088. //collisions, if defined. otherwise, default is true
  62089. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  62090. scene.collisionsEnabled = parsedData.collisionsEnabled;
  62091. }
  62092. scene.workerCollisions = !!parsedData.workerCollisions;
  62093. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  62094. if (!container) {
  62095. return false;
  62096. }
  62097. if (parsedData.autoAnimate) {
  62098. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  62099. }
  62100. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  62101. scene.setActiveCameraByID(parsedData.activeCameraID);
  62102. }
  62103. // Environment texture
  62104. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  62105. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  62106. if (parsedData.createDefaultSkybox === true) {
  62107. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  62108. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  62109. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  62110. }
  62111. }
  62112. // Finish
  62113. return true;
  62114. }
  62115. catch (err) {
  62116. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  62117. if (onError) {
  62118. onError(msg, err);
  62119. }
  62120. else {
  62121. BABYLON.Tools.Log(msg);
  62122. throw err;
  62123. }
  62124. }
  62125. finally {
  62126. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62127. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62128. }
  62129. }
  62130. return false;
  62131. },
  62132. loadAssetContainer: function (scene, data, rootUrl, onError) {
  62133. var container = loadAssetContainer(scene, data, rootUrl, onError);
  62134. return container;
  62135. }
  62136. });
  62137. })(BABYLON || (BABYLON = {}));
  62138. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  62139. var BABYLON;
  62140. (function (BABYLON) {
  62141. var FilesInput = /** @class */ (function () {
  62142. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  62143. this.onProcessFileCallback = function () { return true; };
  62144. this._engine = engine;
  62145. this._currentScene = scene;
  62146. this._sceneLoadedCallback = sceneLoadedCallback;
  62147. this._progressCallback = progressCallback;
  62148. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  62149. this._textureLoadingCallback = textureLoadingCallback;
  62150. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  62151. this._onReloadCallback = onReloadCallback;
  62152. this._errorCallback = errorCallback;
  62153. }
  62154. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  62155. var _this = this;
  62156. if (elementToMonitor) {
  62157. this._elementToMonitor = elementToMonitor;
  62158. this._dragEnterHandler = function (e) { _this.drag(e); };
  62159. this._dragOverHandler = function (e) { _this.drag(e); };
  62160. this._dropHandler = function (e) { _this.drop(e); };
  62161. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  62162. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  62163. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  62164. }
  62165. };
  62166. FilesInput.prototype.dispose = function () {
  62167. if (!this._elementToMonitor) {
  62168. return;
  62169. }
  62170. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  62171. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  62172. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  62173. };
  62174. FilesInput.prototype.renderFunction = function () {
  62175. if (this._additionalRenderLoopLogicCallback) {
  62176. this._additionalRenderLoopLogicCallback();
  62177. }
  62178. if (this._currentScene) {
  62179. if (this._textureLoadingCallback) {
  62180. var remaining = this._currentScene.getWaitingItemsCount();
  62181. if (remaining > 0) {
  62182. this._textureLoadingCallback(remaining);
  62183. }
  62184. }
  62185. this._currentScene.render();
  62186. }
  62187. };
  62188. FilesInput.prototype.drag = function (e) {
  62189. e.stopPropagation();
  62190. e.preventDefault();
  62191. };
  62192. FilesInput.prototype.drop = function (eventDrop) {
  62193. eventDrop.stopPropagation();
  62194. eventDrop.preventDefault();
  62195. this.loadFiles(eventDrop);
  62196. };
  62197. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  62198. var _this = this;
  62199. var reader = folder.createReader();
  62200. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  62201. reader.readEntries(function (entries) {
  62202. remaining.count += entries.length;
  62203. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  62204. var entry = entries_1[_i];
  62205. if (entry.isFile) {
  62206. entry.file(function (file) {
  62207. file.correctName = relativePath + file.name;
  62208. files.push(file);
  62209. if (--remaining.count === 0) {
  62210. callback();
  62211. }
  62212. });
  62213. }
  62214. else if (entry.isDirectory) {
  62215. _this._traverseFolder(entry, files, remaining, callback);
  62216. }
  62217. }
  62218. if (--remaining.count) {
  62219. callback();
  62220. }
  62221. });
  62222. };
  62223. FilesInput.prototype._processFiles = function (files) {
  62224. for (var i = 0; i < files.length; i++) {
  62225. var name = files[i].correctName.toLowerCase();
  62226. var extension = name.split('.').pop();
  62227. if (!this.onProcessFileCallback(files[i], name, extension)) {
  62228. continue;
  62229. }
  62230. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  62231. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  62232. this._sceneFileToLoad = files[i];
  62233. }
  62234. else {
  62235. FilesInput.FilesToLoad[name] = files[i];
  62236. }
  62237. }
  62238. };
  62239. FilesInput.prototype.loadFiles = function (event) {
  62240. var _this = this;
  62241. if (this._startingProcessingFilesCallback)
  62242. this._startingProcessingFilesCallback();
  62243. // Handling data transfer via drag'n'drop
  62244. if (event && event.dataTransfer && event.dataTransfer.files) {
  62245. this._filesToLoad = event.dataTransfer.files;
  62246. }
  62247. // Handling files from input files
  62248. if (event && event.target && event.target.files) {
  62249. this._filesToLoad = event.target.files;
  62250. }
  62251. if (this._filesToLoad && this._filesToLoad.length > 0) {
  62252. var files_1 = new Array();
  62253. var folders = [];
  62254. var items = event.dataTransfer ? event.dataTransfer.items : null;
  62255. for (var i = 0; i < this._filesToLoad.length; i++) {
  62256. var fileToLoad = this._filesToLoad[i];
  62257. var name_1 = fileToLoad.name.toLowerCase();
  62258. var entry = void 0;
  62259. fileToLoad.correctName = name_1;
  62260. if (items) {
  62261. var item = items[i];
  62262. if (item.getAsEntry) {
  62263. entry = item.getAsEntry();
  62264. }
  62265. else if (item.webkitGetAsEntry) {
  62266. entry = item.webkitGetAsEntry();
  62267. }
  62268. }
  62269. if (!entry) {
  62270. files_1.push(fileToLoad);
  62271. }
  62272. else {
  62273. if (entry.isDirectory) {
  62274. folders.push(entry);
  62275. }
  62276. else {
  62277. files_1.push(fileToLoad);
  62278. }
  62279. }
  62280. }
  62281. if (folders.length === 0) {
  62282. this._processFiles(files_1);
  62283. this._processReload();
  62284. }
  62285. else {
  62286. var remaining = { count: folders.length };
  62287. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  62288. var folder = folders_1[_i];
  62289. this._traverseFolder(folder, files_1, remaining, function () {
  62290. _this._processFiles(files_1);
  62291. if (remaining.count === 0) {
  62292. _this._processReload();
  62293. }
  62294. });
  62295. }
  62296. }
  62297. }
  62298. };
  62299. FilesInput.prototype._processReload = function () {
  62300. if (this._onReloadCallback) {
  62301. this._onReloadCallback(this._sceneFileToLoad);
  62302. }
  62303. else {
  62304. this.reload();
  62305. }
  62306. };
  62307. FilesInput.prototype.reload = function () {
  62308. var _this = this;
  62309. // If a scene file has been provided
  62310. if (this._sceneFileToLoad) {
  62311. if (this._currentScene) {
  62312. if (BABYLON.Tools.errorsCount > 0) {
  62313. BABYLON.Tools.ClearLogCache();
  62314. }
  62315. this._engine.stopRenderLoop();
  62316. this._currentScene.dispose();
  62317. }
  62318. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  62319. if (_this._progressCallback) {
  62320. _this._progressCallback(progress);
  62321. }
  62322. }).then(function (scene) {
  62323. _this._currentScene = scene;
  62324. if (_this._sceneLoadedCallback) {
  62325. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  62326. }
  62327. // Wait for textures and shaders to be ready
  62328. _this._currentScene.executeWhenReady(function () {
  62329. _this._engine.runRenderLoop(function () {
  62330. _this.renderFunction();
  62331. });
  62332. });
  62333. }).catch(function (error) {
  62334. if (_this._errorCallback) {
  62335. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  62336. }
  62337. });
  62338. }
  62339. else {
  62340. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  62341. }
  62342. };
  62343. FilesInput.FilesToLoad = {};
  62344. return FilesInput;
  62345. }());
  62346. BABYLON.FilesInput = FilesInput;
  62347. })(BABYLON || (BABYLON = {}));
  62348. //# sourceMappingURL=babylon.filesInput.js.map
  62349. var BABYLON;
  62350. (function (BABYLON) {
  62351. /**
  62352. * This class implement a typical dictionary using a string as key and the generic type T as value.
  62353. * The underlying implementation relies on an associative array to ensure the best performances.
  62354. * The value can be anything including 'null' but except 'undefined'
  62355. */
  62356. var StringDictionary = /** @class */ (function () {
  62357. function StringDictionary() {
  62358. this._count = 0;
  62359. this._data = {};
  62360. }
  62361. /**
  62362. * This will clear this dictionary and copy the content from the 'source' one.
  62363. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  62364. * @param source the dictionary to take the content from and copy to this dictionary
  62365. */
  62366. StringDictionary.prototype.copyFrom = function (source) {
  62367. var _this = this;
  62368. this.clear();
  62369. source.forEach(function (t, v) { return _this.add(t, v); });
  62370. };
  62371. /**
  62372. * Get a value based from its key
  62373. * @param key the given key to get the matching value from
  62374. * @return the value if found, otherwise undefined is returned
  62375. */
  62376. StringDictionary.prototype.get = function (key) {
  62377. var val = this._data[key];
  62378. if (val !== undefined) {
  62379. return val;
  62380. }
  62381. return undefined;
  62382. };
  62383. /**
  62384. * Get a value from its key or add it if it doesn't exist.
  62385. * This method will ensure you that a given key/data will be present in the dictionary.
  62386. * @param key the given key to get the matching value from
  62387. * @param factory the factory that will create the value if the key is not present in the dictionary.
  62388. * The factory will only be invoked if there's no data for the given key.
  62389. * @return the value corresponding to the key.
  62390. */
  62391. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  62392. var val = this.get(key);
  62393. if (val !== undefined) {
  62394. return val;
  62395. }
  62396. val = factory(key);
  62397. if (val) {
  62398. this.add(key, val);
  62399. }
  62400. return val;
  62401. };
  62402. /**
  62403. * Get a value from its key if present in the dictionary otherwise add it
  62404. * @param key the key to get the value from
  62405. * @param val if there's no such key/value pair in the dictionary add it with this value
  62406. * @return the value corresponding to the key
  62407. */
  62408. StringDictionary.prototype.getOrAdd = function (key, val) {
  62409. var curVal = this.get(key);
  62410. if (curVal !== undefined) {
  62411. return curVal;
  62412. }
  62413. this.add(key, val);
  62414. return val;
  62415. };
  62416. /**
  62417. * Check if there's a given key in the dictionary
  62418. * @param key the key to check for
  62419. * @return true if the key is present, false otherwise
  62420. */
  62421. StringDictionary.prototype.contains = function (key) {
  62422. return this._data[key] !== undefined;
  62423. };
  62424. /**
  62425. * Add a new key and its corresponding value
  62426. * @param key the key to add
  62427. * @param value the value corresponding to the key
  62428. * @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
  62429. */
  62430. StringDictionary.prototype.add = function (key, value) {
  62431. if (this._data[key] !== undefined) {
  62432. return false;
  62433. }
  62434. this._data[key] = value;
  62435. ++this._count;
  62436. return true;
  62437. };
  62438. StringDictionary.prototype.set = function (key, value) {
  62439. if (this._data[key] === undefined) {
  62440. return false;
  62441. }
  62442. this._data[key] = value;
  62443. return true;
  62444. };
  62445. /**
  62446. * Get the element of the given key and remove it from the dictionary
  62447. * @param key
  62448. */
  62449. StringDictionary.prototype.getAndRemove = function (key) {
  62450. var val = this.get(key);
  62451. if (val !== undefined) {
  62452. delete this._data[key];
  62453. --this._count;
  62454. return val;
  62455. }
  62456. return null;
  62457. };
  62458. /**
  62459. * Remove a key/value from the dictionary.
  62460. * @param key the key to remove
  62461. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  62462. */
  62463. StringDictionary.prototype.remove = function (key) {
  62464. if (this.contains(key)) {
  62465. delete this._data[key];
  62466. --this._count;
  62467. return true;
  62468. }
  62469. return false;
  62470. };
  62471. /**
  62472. * Clear the whole content of the dictionary
  62473. */
  62474. StringDictionary.prototype.clear = function () {
  62475. this._data = {};
  62476. this._count = 0;
  62477. };
  62478. Object.defineProperty(StringDictionary.prototype, "count", {
  62479. get: function () {
  62480. return this._count;
  62481. },
  62482. enumerable: true,
  62483. configurable: true
  62484. });
  62485. /**
  62486. * Execute a callback on each key/val of the dictionary.
  62487. * Note that you can remove any element in this dictionary in the callback implementation
  62488. * @param callback the callback to execute on a given key/value pair
  62489. */
  62490. StringDictionary.prototype.forEach = function (callback) {
  62491. for (var cur in this._data) {
  62492. var val = this._data[cur];
  62493. callback(cur, val);
  62494. }
  62495. };
  62496. /**
  62497. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  62498. * If the callback returns null or undefined the method will iterate to the next key/value pair
  62499. * Note that you can remove any element in this dictionary in the callback implementation
  62500. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  62501. */
  62502. StringDictionary.prototype.first = function (callback) {
  62503. for (var cur in this._data) {
  62504. var val = this._data[cur];
  62505. var res = callback(cur, val);
  62506. if (res) {
  62507. return res;
  62508. }
  62509. }
  62510. return null;
  62511. };
  62512. return StringDictionary;
  62513. }());
  62514. BABYLON.StringDictionary = StringDictionary;
  62515. })(BABYLON || (BABYLON = {}));
  62516. //# sourceMappingURL=babylon.stringDictionary.js.map
  62517. var BABYLON;
  62518. (function (BABYLON) {
  62519. var Tags = /** @class */ (function () {
  62520. function Tags() {
  62521. }
  62522. Tags.EnableFor = function (obj) {
  62523. obj._tags = obj._tags || {};
  62524. obj.hasTags = function () {
  62525. return Tags.HasTags(obj);
  62526. };
  62527. obj.addTags = function (tagsString) {
  62528. return Tags.AddTagsTo(obj, tagsString);
  62529. };
  62530. obj.removeTags = function (tagsString) {
  62531. return Tags.RemoveTagsFrom(obj, tagsString);
  62532. };
  62533. obj.matchesTagsQuery = function (tagsQuery) {
  62534. return Tags.MatchesQuery(obj, tagsQuery);
  62535. };
  62536. };
  62537. Tags.DisableFor = function (obj) {
  62538. delete obj._tags;
  62539. delete obj.hasTags;
  62540. delete obj.addTags;
  62541. delete obj.removeTags;
  62542. delete obj.matchesTagsQuery;
  62543. };
  62544. Tags.HasTags = function (obj) {
  62545. if (!obj._tags) {
  62546. return false;
  62547. }
  62548. return !BABYLON.Tools.IsEmpty(obj._tags);
  62549. };
  62550. Tags.GetTags = function (obj, asString) {
  62551. if (asString === void 0) { asString = true; }
  62552. if (!obj._tags) {
  62553. return null;
  62554. }
  62555. if (asString) {
  62556. var tagsArray = [];
  62557. for (var tag in obj._tags) {
  62558. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  62559. tagsArray.push(tag);
  62560. }
  62561. }
  62562. return tagsArray.join(" ");
  62563. }
  62564. else {
  62565. return obj._tags;
  62566. }
  62567. };
  62568. // the tags 'true' and 'false' are reserved and cannot be used as tags
  62569. // a tag cannot start with '||', '&&', and '!'
  62570. // it cannot contain whitespaces
  62571. Tags.AddTagsTo = function (obj, tagsString) {
  62572. if (!tagsString) {
  62573. return;
  62574. }
  62575. if (typeof tagsString !== "string") {
  62576. return;
  62577. }
  62578. var tags = tagsString.split(" ");
  62579. tags.forEach(function (tag, index, array) {
  62580. Tags._AddTagTo(obj, tag);
  62581. });
  62582. };
  62583. Tags._AddTagTo = function (obj, tag) {
  62584. tag = tag.trim();
  62585. if (tag === "" || tag === "true" || tag === "false") {
  62586. return;
  62587. }
  62588. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  62589. return;
  62590. }
  62591. Tags.EnableFor(obj);
  62592. obj._tags[tag] = true;
  62593. };
  62594. Tags.RemoveTagsFrom = function (obj, tagsString) {
  62595. if (!Tags.HasTags(obj)) {
  62596. return;
  62597. }
  62598. var tags = tagsString.split(" ");
  62599. for (var t in tags) {
  62600. Tags._RemoveTagFrom(obj, tags[t]);
  62601. }
  62602. };
  62603. Tags._RemoveTagFrom = function (obj, tag) {
  62604. delete obj._tags[tag];
  62605. };
  62606. Tags.MatchesQuery = function (obj, tagsQuery) {
  62607. if (tagsQuery === undefined) {
  62608. return true;
  62609. }
  62610. if (tagsQuery === "") {
  62611. return Tags.HasTags(obj);
  62612. }
  62613. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  62614. };
  62615. return Tags;
  62616. }());
  62617. BABYLON.Tags = Tags;
  62618. })(BABYLON || (BABYLON = {}));
  62619. //# sourceMappingURL=babylon.tags.js.map
  62620. var BABYLON;
  62621. (function (BABYLON) {
  62622. var AndOrNotEvaluator = /** @class */ (function () {
  62623. function AndOrNotEvaluator() {
  62624. }
  62625. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  62626. if (!query.match(/\([^\(\)]*\)/g)) {
  62627. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  62628. }
  62629. else {
  62630. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  62631. // remove parenthesis
  62632. r = r.slice(1, r.length - 1);
  62633. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  62634. });
  62635. }
  62636. if (query === "true") {
  62637. return true;
  62638. }
  62639. if (query === "false") {
  62640. return false;
  62641. }
  62642. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  62643. };
  62644. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  62645. evaluateCallback = evaluateCallback || (function (r) {
  62646. return r === "true" ? true : false;
  62647. });
  62648. var result;
  62649. var or = parenthesisContent.split("||");
  62650. for (var i in or) {
  62651. if (or.hasOwnProperty(i)) {
  62652. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  62653. var and = ori.split("&&");
  62654. if (and.length > 1) {
  62655. for (var j = 0; j < and.length; ++j) {
  62656. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  62657. if (andj !== "true" && andj !== "false") {
  62658. if (andj[0] === "!") {
  62659. result = !evaluateCallback(andj.substring(1));
  62660. }
  62661. else {
  62662. result = evaluateCallback(andj);
  62663. }
  62664. }
  62665. else {
  62666. result = andj === "true" ? true : false;
  62667. }
  62668. if (!result) {
  62669. ori = "false";
  62670. break;
  62671. }
  62672. }
  62673. }
  62674. if (result || ori === "true") {
  62675. result = true;
  62676. break;
  62677. }
  62678. // result equals false (or undefined)
  62679. if (ori !== "true" && ori !== "false") {
  62680. if (ori[0] === "!") {
  62681. result = !evaluateCallback(ori.substring(1));
  62682. }
  62683. else {
  62684. result = evaluateCallback(ori);
  62685. }
  62686. }
  62687. else {
  62688. result = ori === "true" ? true : false;
  62689. }
  62690. }
  62691. }
  62692. // the whole parenthesis scope is replaced by 'true' or 'false'
  62693. return result ? "true" : "false";
  62694. };
  62695. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  62696. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  62697. // remove whitespaces
  62698. r = r.replace(/[\s]/g, function () { return ""; });
  62699. return r.length % 2 ? "!" : "";
  62700. });
  62701. booleanString = booleanString.trim();
  62702. if (booleanString === "!true") {
  62703. booleanString = "false";
  62704. }
  62705. else if (booleanString === "!false") {
  62706. booleanString = "true";
  62707. }
  62708. return booleanString;
  62709. };
  62710. return AndOrNotEvaluator;
  62711. }());
  62712. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  62713. })(BABYLON || (BABYLON = {}));
  62714. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  62715. var BABYLON;
  62716. (function (BABYLON) {
  62717. var Database = /** @class */ (function () {
  62718. function Database(urlToScene, callbackManifestChecked) {
  62719. // Handling various flavors of prefixed version of IndexedDB
  62720. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  62721. this.callbackManifestChecked = callbackManifestChecked;
  62722. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  62723. this.db = null;
  62724. this._enableSceneOffline = false;
  62725. this._enableTexturesOffline = false;
  62726. this.manifestVersionFound = 0;
  62727. this.mustUpdateRessources = false;
  62728. this.hasReachedQuota = false;
  62729. if (!Database.IDBStorageEnabled) {
  62730. this.callbackManifestChecked(true);
  62731. }
  62732. else {
  62733. this.checkManifestFile();
  62734. }
  62735. }
  62736. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  62737. get: function () {
  62738. return this._enableSceneOffline;
  62739. },
  62740. enumerable: true,
  62741. configurable: true
  62742. });
  62743. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  62744. get: function () {
  62745. return this._enableTexturesOffline;
  62746. },
  62747. enumerable: true,
  62748. configurable: true
  62749. });
  62750. Database.prototype.checkManifestFile = function () {
  62751. var _this = this;
  62752. var noManifestFile = function () {
  62753. _this._enableSceneOffline = false;
  62754. _this._enableTexturesOffline = false;
  62755. _this.callbackManifestChecked(false);
  62756. };
  62757. var timeStampUsed = false;
  62758. var manifestURL = this.currentSceneUrl + ".manifest";
  62759. var xhr = new XMLHttpRequest();
  62760. if (navigator.onLine) {
  62761. // Adding a timestamp to by-pass browsers' cache
  62762. timeStampUsed = true;
  62763. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  62764. }
  62765. xhr.open("GET", manifestURL, true);
  62766. xhr.addEventListener("load", function () {
  62767. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  62768. try {
  62769. var manifestFile = JSON.parse(xhr.response);
  62770. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  62771. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  62772. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  62773. _this.manifestVersionFound = manifestFile.version;
  62774. }
  62775. if (_this.callbackManifestChecked) {
  62776. _this.callbackManifestChecked(true);
  62777. }
  62778. }
  62779. catch (ex) {
  62780. noManifestFile();
  62781. }
  62782. }
  62783. else {
  62784. noManifestFile();
  62785. }
  62786. }, false);
  62787. xhr.addEventListener("error", function (event) {
  62788. if (timeStampUsed) {
  62789. timeStampUsed = false;
  62790. // Let's retry without the timeStamp
  62791. // It could fail when coupled with HTML5 Offline API
  62792. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  62793. xhr.open("GET", retryManifestURL, true);
  62794. xhr.send();
  62795. }
  62796. else {
  62797. noManifestFile();
  62798. }
  62799. }, false);
  62800. try {
  62801. xhr.send();
  62802. }
  62803. catch (ex) {
  62804. BABYLON.Tools.Error("Error on XHR send request.");
  62805. this.callbackManifestChecked(false);
  62806. }
  62807. };
  62808. Database.prototype.openAsync = function (successCallback, errorCallback) {
  62809. var _this = this;
  62810. var handleError = function () {
  62811. _this.isSupported = false;
  62812. if (errorCallback)
  62813. errorCallback();
  62814. };
  62815. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  62816. // Your browser doesn't support IndexedDB
  62817. this.isSupported = false;
  62818. if (errorCallback)
  62819. errorCallback();
  62820. }
  62821. else {
  62822. // If the DB hasn't been opened or created yet
  62823. if (!this.db) {
  62824. this.hasReachedQuota = false;
  62825. this.isSupported = true;
  62826. var request = this.idbFactory.open("babylonjs", 1);
  62827. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  62828. request.onerror = function (event) {
  62829. handleError();
  62830. };
  62831. // executes when a version change transaction cannot complete due to other active transactions
  62832. request.onblocked = function (event) {
  62833. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  62834. handleError();
  62835. };
  62836. // DB has been opened successfully
  62837. request.onsuccess = function (event) {
  62838. _this.db = request.result;
  62839. successCallback();
  62840. };
  62841. // Initialization of the DB. Creating Scenes & Textures stores
  62842. request.onupgradeneeded = function (event) {
  62843. _this.db = (event.target).result;
  62844. if (_this.db) {
  62845. try {
  62846. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  62847. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  62848. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  62849. }
  62850. catch (ex) {
  62851. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  62852. handleError();
  62853. }
  62854. }
  62855. };
  62856. }
  62857. else {
  62858. if (successCallback)
  62859. successCallback();
  62860. }
  62861. }
  62862. };
  62863. Database.prototype.loadImageFromDB = function (url, image) {
  62864. var _this = this;
  62865. var completeURL = Database.ReturnFullUrlLocation(url);
  62866. var saveAndLoadImage = function () {
  62867. if (!_this.hasReachedQuota && _this.db !== null) {
  62868. // the texture is not yet in the DB, let's try to save it
  62869. _this._saveImageIntoDBAsync(completeURL, image);
  62870. }
  62871. else {
  62872. image.src = url;
  62873. }
  62874. };
  62875. if (!this.mustUpdateRessources) {
  62876. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  62877. }
  62878. else {
  62879. saveAndLoadImage();
  62880. }
  62881. };
  62882. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  62883. if (this.isSupported && this.db !== null) {
  62884. var texture;
  62885. var transaction = this.db.transaction(["textures"]);
  62886. transaction.onabort = function (event) {
  62887. image.src = url;
  62888. };
  62889. transaction.oncomplete = function (event) {
  62890. var blobTextureURL;
  62891. if (texture) {
  62892. var URL = window.URL || window.webkitURL;
  62893. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  62894. image.onerror = function () {
  62895. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  62896. image.src = url;
  62897. };
  62898. image.src = blobTextureURL;
  62899. }
  62900. else {
  62901. notInDBCallback();
  62902. }
  62903. };
  62904. var getRequest = transaction.objectStore("textures").get(url);
  62905. getRequest.onsuccess = function (event) {
  62906. texture = (event.target).result;
  62907. };
  62908. getRequest.onerror = function (event) {
  62909. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  62910. image.src = url;
  62911. };
  62912. }
  62913. else {
  62914. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62915. image.src = url;
  62916. }
  62917. };
  62918. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  62919. var _this = this;
  62920. if (this.isSupported) {
  62921. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  62922. var generateBlobUrl = function () {
  62923. var blobTextureURL;
  62924. if (blob) {
  62925. var URL = window.URL || window.webkitURL;
  62926. try {
  62927. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  62928. }
  62929. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  62930. catch (ex) {
  62931. blobTextureURL = URL.createObjectURL(blob);
  62932. }
  62933. }
  62934. if (blobTextureURL) {
  62935. image.src = blobTextureURL;
  62936. }
  62937. };
  62938. if (Database.IsUASupportingBlobStorage) {
  62939. var xhr = new XMLHttpRequest(), blob;
  62940. xhr.open("GET", url, true);
  62941. xhr.responseType = "blob";
  62942. xhr.addEventListener("load", function () {
  62943. if (xhr.status === 200 && _this.db) {
  62944. // Blob as response (XHR2)
  62945. blob = xhr.response;
  62946. var transaction = _this.db.transaction(["textures"], "readwrite");
  62947. // the transaction could abort because of a QuotaExceededError error
  62948. transaction.onabort = function (event) {
  62949. try {
  62950. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  62951. var srcElement = (event.srcElement || event.target);
  62952. var error = srcElement.error;
  62953. if (error && error.name === "QuotaExceededError") {
  62954. _this.hasReachedQuota = true;
  62955. }
  62956. }
  62957. catch (ex) { }
  62958. generateBlobUrl();
  62959. };
  62960. transaction.oncomplete = function (event) {
  62961. generateBlobUrl();
  62962. };
  62963. var newTexture = { textureUrl: url, data: blob };
  62964. try {
  62965. // Put the blob into the dabase
  62966. var addRequest = transaction.objectStore("textures").put(newTexture);
  62967. addRequest.onsuccess = function (event) {
  62968. };
  62969. addRequest.onerror = function (event) {
  62970. generateBlobUrl();
  62971. };
  62972. }
  62973. catch (ex) {
  62974. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  62975. if (ex.code === 25) {
  62976. Database.IsUASupportingBlobStorage = false;
  62977. }
  62978. image.src = url;
  62979. }
  62980. }
  62981. else {
  62982. image.src = url;
  62983. }
  62984. }, false);
  62985. xhr.addEventListener("error", function (event) {
  62986. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  62987. image.src = url;
  62988. }, false);
  62989. xhr.send();
  62990. }
  62991. else {
  62992. image.src = url;
  62993. }
  62994. }
  62995. else {
  62996. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62997. image.src = url;
  62998. }
  62999. };
  63000. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  63001. var _this = this;
  63002. var updateVersion = function () {
  63003. // the version is not yet in the DB or we need to update it
  63004. _this._saveVersionIntoDBAsync(url, versionLoaded);
  63005. };
  63006. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  63007. };
  63008. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  63009. var _this = this;
  63010. if (this.isSupported && this.db) {
  63011. var version;
  63012. try {
  63013. var transaction = this.db.transaction(["versions"]);
  63014. transaction.oncomplete = function (event) {
  63015. if (version) {
  63016. // If the version in the JSON file is > than the version in DB
  63017. if (_this.manifestVersionFound > version.data) {
  63018. _this.mustUpdateRessources = true;
  63019. updateInDBCallback();
  63020. }
  63021. else {
  63022. callback(version.data);
  63023. }
  63024. }
  63025. else {
  63026. _this.mustUpdateRessources = true;
  63027. updateInDBCallback();
  63028. }
  63029. };
  63030. transaction.onabort = function (event) {
  63031. callback(-1);
  63032. };
  63033. var getRequest = transaction.objectStore("versions").get(url);
  63034. getRequest.onsuccess = function (event) {
  63035. version = (event.target).result;
  63036. };
  63037. getRequest.onerror = function (event) {
  63038. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  63039. callback(-1);
  63040. };
  63041. }
  63042. catch (ex) {
  63043. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  63044. callback(-1);
  63045. }
  63046. }
  63047. else {
  63048. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63049. callback(-1);
  63050. }
  63051. };
  63052. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  63053. var _this = this;
  63054. if (this.isSupported && !this.hasReachedQuota && this.db) {
  63055. try {
  63056. // Open a transaction to the database
  63057. var transaction = this.db.transaction(["versions"], "readwrite");
  63058. // the transaction could abort because of a QuotaExceededError error
  63059. transaction.onabort = function (event) {
  63060. try {
  63061. var error = event.srcElement['error'];
  63062. if (error && error.name === "QuotaExceededError") {
  63063. _this.hasReachedQuota = true;
  63064. }
  63065. }
  63066. catch (ex) { }
  63067. callback(-1);
  63068. };
  63069. transaction.oncomplete = function (event) {
  63070. callback(_this.manifestVersionFound);
  63071. };
  63072. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  63073. // Put the scene into the database
  63074. var addRequest = transaction.objectStore("versions").put(newVersion);
  63075. addRequest.onsuccess = function (event) {
  63076. };
  63077. addRequest.onerror = function (event) {
  63078. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  63079. };
  63080. }
  63081. catch (ex) {
  63082. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  63083. callback(-1);
  63084. }
  63085. }
  63086. else {
  63087. callback(-1);
  63088. }
  63089. };
  63090. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  63091. var _this = this;
  63092. var completeUrl = Database.ReturnFullUrlLocation(url);
  63093. var saveAndLoadFile = function () {
  63094. // the scene is not yet in the DB, let's try to save it
  63095. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  63096. };
  63097. this._checkVersionFromDB(completeUrl, function (version) {
  63098. if (version !== -1) {
  63099. if (!_this.mustUpdateRessources) {
  63100. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  63101. }
  63102. else {
  63103. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  63104. }
  63105. }
  63106. else {
  63107. if (errorCallback) {
  63108. errorCallback();
  63109. }
  63110. }
  63111. });
  63112. };
  63113. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  63114. if (this.isSupported && this.db) {
  63115. var targetStore;
  63116. if (url.indexOf(".babylon") !== -1) {
  63117. targetStore = "scenes";
  63118. }
  63119. else {
  63120. targetStore = "textures";
  63121. }
  63122. var file;
  63123. var transaction = this.db.transaction([targetStore]);
  63124. transaction.oncomplete = function (event) {
  63125. if (file) {
  63126. callback(file.data);
  63127. }
  63128. else {
  63129. notInDBCallback();
  63130. }
  63131. };
  63132. transaction.onabort = function (event) {
  63133. notInDBCallback();
  63134. };
  63135. var getRequest = transaction.objectStore(targetStore).get(url);
  63136. getRequest.onsuccess = function (event) {
  63137. file = (event.target).result;
  63138. };
  63139. getRequest.onerror = function (event) {
  63140. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  63141. notInDBCallback();
  63142. };
  63143. }
  63144. else {
  63145. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63146. callback();
  63147. }
  63148. };
  63149. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  63150. var _this = this;
  63151. if (this.isSupported) {
  63152. var targetStore;
  63153. if (url.indexOf(".babylon") !== -1) {
  63154. targetStore = "scenes";
  63155. }
  63156. else {
  63157. targetStore = "textures";
  63158. }
  63159. // Create XHR
  63160. var xhr = new XMLHttpRequest();
  63161. var fileData;
  63162. xhr.open("GET", url, true);
  63163. if (useArrayBuffer) {
  63164. xhr.responseType = "arraybuffer";
  63165. }
  63166. if (progressCallback) {
  63167. xhr.onprogress = progressCallback;
  63168. }
  63169. xhr.addEventListener("load", function () {
  63170. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  63171. // Blob as response (XHR2)
  63172. //fileData = xhr.responseText;
  63173. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  63174. if (!_this.hasReachedQuota && _this.db) {
  63175. // Open a transaction to the database
  63176. var transaction = _this.db.transaction([targetStore], "readwrite");
  63177. // the transaction could abort because of a QuotaExceededError error
  63178. transaction.onabort = function (event) {
  63179. try {
  63180. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  63181. var error = event.srcElement['error'];
  63182. if (error && error.name === "QuotaExceededError") {
  63183. _this.hasReachedQuota = true;
  63184. }
  63185. }
  63186. catch (ex) { }
  63187. callback(fileData);
  63188. };
  63189. transaction.oncomplete = function (event) {
  63190. callback(fileData);
  63191. };
  63192. var newFile;
  63193. if (targetStore === "scenes") {
  63194. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  63195. }
  63196. else {
  63197. newFile = { textureUrl: url, data: fileData };
  63198. }
  63199. try {
  63200. // Put the scene into the database
  63201. var addRequest = transaction.objectStore(targetStore).put(newFile);
  63202. addRequest.onsuccess = function (event) {
  63203. };
  63204. addRequest.onerror = function (event) {
  63205. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  63206. };
  63207. }
  63208. catch (ex) {
  63209. callback(fileData);
  63210. }
  63211. }
  63212. else {
  63213. callback(fileData);
  63214. }
  63215. }
  63216. else {
  63217. callback();
  63218. }
  63219. }, false);
  63220. xhr.addEventListener("error", function (event) {
  63221. BABYLON.Tools.Error("error on XHR request.");
  63222. callback();
  63223. }, false);
  63224. xhr.send();
  63225. }
  63226. else {
  63227. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63228. callback();
  63229. }
  63230. };
  63231. Database.IsUASupportingBlobStorage = true;
  63232. Database.IDBStorageEnabled = true;
  63233. Database.parseURL = function (url) {
  63234. var a = document.createElement('a');
  63235. a.href = url;
  63236. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  63237. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  63238. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  63239. return absLocation;
  63240. };
  63241. Database.ReturnFullUrlLocation = function (url) {
  63242. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  63243. return (Database.parseURL(window.location.href) + url);
  63244. }
  63245. else {
  63246. return url;
  63247. }
  63248. };
  63249. return Database;
  63250. }());
  63251. BABYLON.Database = Database;
  63252. })(BABYLON || (BABYLON = {}));
  63253. //# sourceMappingURL=babylon.database.js.map
  63254. var BABYLON;
  63255. (function (BABYLON) {
  63256. var FresnelParameters = /** @class */ (function () {
  63257. function FresnelParameters() {
  63258. this._isEnabled = true;
  63259. this.leftColor = BABYLON.Color3.White();
  63260. this.rightColor = BABYLON.Color3.Black();
  63261. this.bias = 0;
  63262. this.power = 1;
  63263. }
  63264. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  63265. get: function () {
  63266. return this._isEnabled;
  63267. },
  63268. set: function (value) {
  63269. if (this._isEnabled === value) {
  63270. return;
  63271. }
  63272. this._isEnabled = value;
  63273. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  63274. },
  63275. enumerable: true,
  63276. configurable: true
  63277. });
  63278. FresnelParameters.prototype.clone = function () {
  63279. var newFresnelParameters = new FresnelParameters();
  63280. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  63281. return newFresnelParameters;
  63282. };
  63283. FresnelParameters.prototype.serialize = function () {
  63284. var serializationObject = {};
  63285. serializationObject.isEnabled = this.isEnabled;
  63286. serializationObject.leftColor = this.leftColor;
  63287. serializationObject.rightColor = this.rightColor;
  63288. serializationObject.bias = this.bias;
  63289. serializationObject.power = this.power;
  63290. return serializationObject;
  63291. };
  63292. FresnelParameters.Parse = function (parsedFresnelParameters) {
  63293. var fresnelParameters = new FresnelParameters();
  63294. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  63295. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  63296. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  63297. fresnelParameters.bias = parsedFresnelParameters.bias;
  63298. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  63299. return fresnelParameters;
  63300. };
  63301. return FresnelParameters;
  63302. }());
  63303. BABYLON.FresnelParameters = FresnelParameters;
  63304. })(BABYLON || (BABYLON = {}));
  63305. //# sourceMappingURL=babylon.fresnelParameters.js.map
  63306. var BABYLON;
  63307. (function (BABYLON) {
  63308. var MultiMaterial = /** @class */ (function (_super) {
  63309. __extends(MultiMaterial, _super);
  63310. function MultiMaterial(name, scene) {
  63311. var _this = _super.call(this, name, scene, true) || this;
  63312. scene.multiMaterials.push(_this);
  63313. _this.subMaterials = new Array();
  63314. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  63315. return _this;
  63316. }
  63317. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  63318. get: function () {
  63319. return this._subMaterials;
  63320. },
  63321. set: function (value) {
  63322. this._subMaterials = value;
  63323. this._hookArray(value);
  63324. },
  63325. enumerable: true,
  63326. configurable: true
  63327. });
  63328. MultiMaterial.prototype._hookArray = function (array) {
  63329. var _this = this;
  63330. var oldPush = array.push;
  63331. array.push = function () {
  63332. var items = [];
  63333. for (var _i = 0; _i < arguments.length; _i++) {
  63334. items[_i] = arguments[_i];
  63335. }
  63336. var result = oldPush.apply(array, items);
  63337. _this._markAllSubMeshesAsTexturesDirty();
  63338. return result;
  63339. };
  63340. var oldSplice = array.splice;
  63341. array.splice = function (index, deleteCount) {
  63342. var deleted = oldSplice.apply(array, [index, deleteCount]);
  63343. _this._markAllSubMeshesAsTexturesDirty();
  63344. return deleted;
  63345. };
  63346. };
  63347. // Properties
  63348. MultiMaterial.prototype.getSubMaterial = function (index) {
  63349. if (index < 0 || index >= this.subMaterials.length) {
  63350. return this.getScene().defaultMaterial;
  63351. }
  63352. return this.subMaterials[index];
  63353. };
  63354. MultiMaterial.prototype.getActiveTextures = function () {
  63355. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  63356. if (subMaterial) {
  63357. return subMaterial.getActiveTextures();
  63358. }
  63359. else {
  63360. return [];
  63361. }
  63362. }));
  63363. var _a;
  63364. };
  63365. // Methods
  63366. MultiMaterial.prototype.getClassName = function () {
  63367. return "MultiMaterial";
  63368. };
  63369. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  63370. for (var index = 0; index < this.subMaterials.length; index++) {
  63371. var subMaterial = this.subMaterials[index];
  63372. if (subMaterial) {
  63373. if (subMaterial.storeEffectOnSubMeshes) {
  63374. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  63375. return false;
  63376. }
  63377. continue;
  63378. }
  63379. if (!subMaterial.isReady(mesh)) {
  63380. return false;
  63381. }
  63382. }
  63383. }
  63384. return true;
  63385. };
  63386. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  63387. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  63388. for (var index = 0; index < this.subMaterials.length; index++) {
  63389. var subMaterial = null;
  63390. var current = this.subMaterials[index];
  63391. if (cloneChildren && current) {
  63392. subMaterial = current.clone(name + "-" + current.name);
  63393. }
  63394. else {
  63395. subMaterial = this.subMaterials[index];
  63396. }
  63397. newMultiMaterial.subMaterials.push(subMaterial);
  63398. }
  63399. return newMultiMaterial;
  63400. };
  63401. MultiMaterial.prototype.serialize = function () {
  63402. var serializationObject = {};
  63403. serializationObject.name = this.name;
  63404. serializationObject.id = this.id;
  63405. if (BABYLON.Tags) {
  63406. serializationObject.tags = BABYLON.Tags.GetTags(this);
  63407. }
  63408. serializationObject.materials = [];
  63409. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  63410. var subMat = this.subMaterials[matIndex];
  63411. if (subMat) {
  63412. serializationObject.materials.push(subMat.id);
  63413. }
  63414. else {
  63415. serializationObject.materials.push(null);
  63416. }
  63417. }
  63418. return serializationObject;
  63419. };
  63420. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  63421. var scene = this.getScene();
  63422. if (!scene) {
  63423. return;
  63424. }
  63425. var index = scene.multiMaterials.indexOf(this);
  63426. if (index >= 0) {
  63427. scene.multiMaterials.splice(index, 1);
  63428. }
  63429. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  63430. };
  63431. return MultiMaterial;
  63432. }(BABYLON.Material));
  63433. BABYLON.MultiMaterial = MultiMaterial;
  63434. })(BABYLON || (BABYLON = {}));
  63435. //# sourceMappingURL=babylon.multiMaterial.js.map
  63436. var BABYLON;
  63437. (function (BABYLON) {
  63438. var FreeCameraTouchInput = /** @class */ (function () {
  63439. function FreeCameraTouchInput() {
  63440. this._offsetX = null;
  63441. this._offsetY = null;
  63442. this._pointerPressed = new Array();
  63443. this.touchAngularSensibility = 200000.0;
  63444. this.touchMoveSensibility = 250.0;
  63445. }
  63446. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  63447. var _this = this;
  63448. var previousPosition = null;
  63449. if (this._pointerInput === undefined) {
  63450. this._onLostFocus = function (evt) {
  63451. _this._offsetX = null;
  63452. _this._offsetY = null;
  63453. };
  63454. this._pointerInput = function (p, s) {
  63455. var evt = p.event;
  63456. if (evt.pointerType === "mouse") {
  63457. return;
  63458. }
  63459. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  63460. if (!noPreventDefault) {
  63461. evt.preventDefault();
  63462. }
  63463. _this._pointerPressed.push(evt.pointerId);
  63464. if (_this._pointerPressed.length !== 1) {
  63465. return;
  63466. }
  63467. previousPosition = {
  63468. x: evt.clientX,
  63469. y: evt.clientY
  63470. };
  63471. }
  63472. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  63473. if (!noPreventDefault) {
  63474. evt.preventDefault();
  63475. }
  63476. var index = _this._pointerPressed.indexOf(evt.pointerId);
  63477. if (index === -1) {
  63478. return;
  63479. }
  63480. _this._pointerPressed.splice(index, 1);
  63481. if (index != 0) {
  63482. return;
  63483. }
  63484. previousPosition = null;
  63485. _this._offsetX = null;
  63486. _this._offsetY = null;
  63487. }
  63488. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  63489. if (!noPreventDefault) {
  63490. evt.preventDefault();
  63491. }
  63492. if (!previousPosition) {
  63493. return;
  63494. }
  63495. var index = _this._pointerPressed.indexOf(evt.pointerId);
  63496. if (index != 0) {
  63497. return;
  63498. }
  63499. _this._offsetX = evt.clientX - previousPosition.x;
  63500. _this._offsetY = -(evt.clientY - previousPosition.y);
  63501. }
  63502. };
  63503. }
  63504. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  63505. if (this._onLostFocus) {
  63506. element.addEventListener("blur", this._onLostFocus);
  63507. }
  63508. };
  63509. FreeCameraTouchInput.prototype.detachControl = function (element) {
  63510. if (this._pointerInput && element) {
  63511. if (this._observer) {
  63512. this.camera.getScene().onPointerObservable.remove(this._observer);
  63513. this._observer = null;
  63514. }
  63515. if (this._onLostFocus) {
  63516. element.removeEventListener("blur", this._onLostFocus);
  63517. this._onLostFocus = null;
  63518. }
  63519. this._pointerPressed = [];
  63520. this._offsetX = null;
  63521. this._offsetY = null;
  63522. }
  63523. };
  63524. FreeCameraTouchInput.prototype.checkInputs = function () {
  63525. if (this._offsetX && this._offsetY) {
  63526. var camera = this.camera;
  63527. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  63528. if (this._pointerPressed.length > 1) {
  63529. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  63530. }
  63531. else {
  63532. var speed = camera._computeLocalCameraSpeed();
  63533. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  63534. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  63535. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  63536. }
  63537. }
  63538. };
  63539. FreeCameraTouchInput.prototype.getClassName = function () {
  63540. return "FreeCameraTouchInput";
  63541. };
  63542. FreeCameraTouchInput.prototype.getSimpleName = function () {
  63543. return "touch";
  63544. };
  63545. __decorate([
  63546. BABYLON.serialize()
  63547. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  63548. __decorate([
  63549. BABYLON.serialize()
  63550. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  63551. return FreeCameraTouchInput;
  63552. }());
  63553. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  63554. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  63555. })(BABYLON || (BABYLON = {}));
  63556. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  63557. var BABYLON;
  63558. (function (BABYLON) {
  63559. // We're mainly based on the logic defined into the FreeCamera code
  63560. var TouchCamera = /** @class */ (function (_super) {
  63561. __extends(TouchCamera, _super);
  63562. //-- end properties for backward compatibility for inputs
  63563. function TouchCamera(name, position, scene) {
  63564. var _this = _super.call(this, name, position, scene) || this;
  63565. _this.inputs.addTouch();
  63566. _this._setupInputs();
  63567. return _this;
  63568. }
  63569. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  63570. //-- Begin properties for backward compatibility for inputs
  63571. get: function () {
  63572. var touch = this.inputs.attached["touch"];
  63573. if (touch)
  63574. return touch.touchAngularSensibility;
  63575. return 0;
  63576. },
  63577. set: function (value) {
  63578. var touch = this.inputs.attached["touch"];
  63579. if (touch)
  63580. touch.touchAngularSensibility = value;
  63581. },
  63582. enumerable: true,
  63583. configurable: true
  63584. });
  63585. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  63586. get: function () {
  63587. var touch = this.inputs.attached["touch"];
  63588. if (touch)
  63589. return touch.touchMoveSensibility;
  63590. return 0;
  63591. },
  63592. set: function (value) {
  63593. var touch = this.inputs.attached["touch"];
  63594. if (touch)
  63595. touch.touchMoveSensibility = value;
  63596. },
  63597. enumerable: true,
  63598. configurable: true
  63599. });
  63600. TouchCamera.prototype.getClassName = function () {
  63601. return "TouchCamera";
  63602. };
  63603. TouchCamera.prototype._setupInputs = function () {
  63604. var mouse = this.inputs.attached["mouse"];
  63605. if (mouse) {
  63606. mouse.touchEnabled = false;
  63607. }
  63608. };
  63609. return TouchCamera;
  63610. }(BABYLON.FreeCamera));
  63611. BABYLON.TouchCamera = TouchCamera;
  63612. })(BABYLON || (BABYLON = {}));
  63613. //# sourceMappingURL=babylon.touchCamera.js.map
  63614. var BABYLON;
  63615. (function (BABYLON) {
  63616. var ProceduralTexture = /** @class */ (function (_super) {
  63617. __extends(ProceduralTexture, _super);
  63618. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  63619. if (fallbackTexture === void 0) { fallbackTexture = null; }
  63620. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63621. if (isCube === void 0) { isCube = false; }
  63622. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63623. _this.isCube = isCube;
  63624. _this.isEnabled = true;
  63625. _this._currentRefreshId = -1;
  63626. _this._refreshRate = 1;
  63627. _this._vertexBuffers = {};
  63628. _this._uniforms = new Array();
  63629. _this._samplers = new Array();
  63630. _this._textures = {};
  63631. _this._floats = {};
  63632. _this._floatsArrays = {};
  63633. _this._colors3 = {};
  63634. _this._colors4 = {};
  63635. _this._vectors2 = {};
  63636. _this._vectors3 = {};
  63637. _this._matrices = {};
  63638. _this._fallbackTextureUsed = false;
  63639. scene._proceduralTextures.push(_this);
  63640. _this._engine = scene.getEngine();
  63641. _this.name = name;
  63642. _this.isRenderTarget = true;
  63643. _this._size = size;
  63644. _this._generateMipMaps = generateMipMaps;
  63645. _this.setFragment(fragment);
  63646. _this._fallbackTexture = fallbackTexture;
  63647. if (isCube) {
  63648. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  63649. _this.setFloat("face", 0);
  63650. }
  63651. else {
  63652. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  63653. }
  63654. // VBO
  63655. var vertices = [];
  63656. vertices.push(1, 1);
  63657. vertices.push(-1, 1);
  63658. vertices.push(-1, -1);
  63659. vertices.push(1, -1);
  63660. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  63661. _this._createIndexBuffer();
  63662. return _this;
  63663. }
  63664. ProceduralTexture.prototype._createIndexBuffer = function () {
  63665. var engine = this._engine;
  63666. // Indices
  63667. var indices = [];
  63668. indices.push(0);
  63669. indices.push(1);
  63670. indices.push(2);
  63671. indices.push(0);
  63672. indices.push(2);
  63673. indices.push(3);
  63674. this._indexBuffer = engine.createIndexBuffer(indices);
  63675. };
  63676. ProceduralTexture.prototype._rebuild = function () {
  63677. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63678. if (vb) {
  63679. vb._rebuild();
  63680. }
  63681. this._createIndexBuffer();
  63682. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63683. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63684. }
  63685. };
  63686. ProceduralTexture.prototype.reset = function () {
  63687. if (this._effect === undefined) {
  63688. return;
  63689. }
  63690. var engine = this._engine;
  63691. engine._releaseEffect(this._effect);
  63692. };
  63693. ProceduralTexture.prototype.isReady = function () {
  63694. var _this = this;
  63695. var engine = this._engine;
  63696. var shaders;
  63697. if (!this._fragment) {
  63698. return false;
  63699. }
  63700. if (this._fallbackTextureUsed) {
  63701. return true;
  63702. }
  63703. if (this._fragment.fragmentElement !== undefined) {
  63704. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  63705. }
  63706. else {
  63707. shaders = { vertex: "procedural", fragment: this._fragment };
  63708. }
  63709. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  63710. _this.releaseInternalTexture();
  63711. if (_this._fallbackTexture) {
  63712. _this._texture = _this._fallbackTexture._texture;
  63713. if (_this._texture) {
  63714. _this._texture.incrementReferences();
  63715. }
  63716. }
  63717. _this._fallbackTextureUsed = true;
  63718. });
  63719. return this._effect.isReady();
  63720. };
  63721. ProceduralTexture.prototype.resetRefreshCounter = function () {
  63722. this._currentRefreshId = -1;
  63723. };
  63724. ProceduralTexture.prototype.setFragment = function (fragment) {
  63725. this._fragment = fragment;
  63726. };
  63727. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  63728. get: function () {
  63729. return this._refreshRate;
  63730. },
  63731. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63732. set: function (value) {
  63733. this._refreshRate = value;
  63734. this.resetRefreshCounter();
  63735. },
  63736. enumerable: true,
  63737. configurable: true
  63738. });
  63739. ProceduralTexture.prototype._shouldRender = function () {
  63740. if (!this.isEnabled || !this.isReady() || !this._texture) {
  63741. return false;
  63742. }
  63743. if (this._fallbackTextureUsed) {
  63744. return false;
  63745. }
  63746. if (this._currentRefreshId === -1) {
  63747. this._currentRefreshId = 1;
  63748. return true;
  63749. }
  63750. if (this.refreshRate === this._currentRefreshId) {
  63751. this._currentRefreshId = 1;
  63752. return true;
  63753. }
  63754. this._currentRefreshId++;
  63755. return false;
  63756. };
  63757. ProceduralTexture.prototype.getRenderSize = function () {
  63758. return this._size;
  63759. };
  63760. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  63761. if (this._fallbackTextureUsed) {
  63762. return;
  63763. }
  63764. this.releaseInternalTexture();
  63765. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  63766. };
  63767. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  63768. if (this._uniforms.indexOf(uniformName) === -1) {
  63769. this._uniforms.push(uniformName);
  63770. }
  63771. };
  63772. ProceduralTexture.prototype.setTexture = function (name, texture) {
  63773. if (this._samplers.indexOf(name) === -1) {
  63774. this._samplers.push(name);
  63775. }
  63776. this._textures[name] = texture;
  63777. return this;
  63778. };
  63779. ProceduralTexture.prototype.setFloat = function (name, value) {
  63780. this._checkUniform(name);
  63781. this._floats[name] = value;
  63782. return this;
  63783. };
  63784. ProceduralTexture.prototype.setFloats = function (name, value) {
  63785. this._checkUniform(name);
  63786. this._floatsArrays[name] = value;
  63787. return this;
  63788. };
  63789. ProceduralTexture.prototype.setColor3 = function (name, value) {
  63790. this._checkUniform(name);
  63791. this._colors3[name] = value;
  63792. return this;
  63793. };
  63794. ProceduralTexture.prototype.setColor4 = function (name, value) {
  63795. this._checkUniform(name);
  63796. this._colors4[name] = value;
  63797. return this;
  63798. };
  63799. ProceduralTexture.prototype.setVector2 = function (name, value) {
  63800. this._checkUniform(name);
  63801. this._vectors2[name] = value;
  63802. return this;
  63803. };
  63804. ProceduralTexture.prototype.setVector3 = function (name, value) {
  63805. this._checkUniform(name);
  63806. this._vectors3[name] = value;
  63807. return this;
  63808. };
  63809. ProceduralTexture.prototype.setMatrix = function (name, value) {
  63810. this._checkUniform(name);
  63811. this._matrices[name] = value;
  63812. return this;
  63813. };
  63814. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  63815. var scene = this.getScene();
  63816. if (!scene) {
  63817. return;
  63818. }
  63819. var engine = this._engine;
  63820. // Render
  63821. engine.enableEffect(this._effect);
  63822. engine.setState(false);
  63823. // Texture
  63824. for (var name in this._textures) {
  63825. this._effect.setTexture(name, this._textures[name]);
  63826. }
  63827. // Float
  63828. for (name in this._floats) {
  63829. this._effect.setFloat(name, this._floats[name]);
  63830. }
  63831. // Floats
  63832. for (name in this._floatsArrays) {
  63833. this._effect.setArray(name, this._floatsArrays[name]);
  63834. }
  63835. // Color3
  63836. for (name in this._colors3) {
  63837. this._effect.setColor3(name, this._colors3[name]);
  63838. }
  63839. // Color4
  63840. for (name in this._colors4) {
  63841. var color = this._colors4[name];
  63842. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  63843. }
  63844. // Vector2
  63845. for (name in this._vectors2) {
  63846. this._effect.setVector2(name, this._vectors2[name]);
  63847. }
  63848. // Vector3
  63849. for (name in this._vectors3) {
  63850. this._effect.setVector3(name, this._vectors3[name]);
  63851. }
  63852. // Matrix
  63853. for (name in this._matrices) {
  63854. this._effect.setMatrix(name, this._matrices[name]);
  63855. }
  63856. if (!this._texture) {
  63857. return;
  63858. }
  63859. if (this.isCube) {
  63860. for (var face = 0; face < 6; face++) {
  63861. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  63862. // VBOs
  63863. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  63864. this._effect.setFloat("face", face);
  63865. // Clear
  63866. engine.clear(scene.clearColor, true, true, true);
  63867. // Draw order
  63868. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  63869. // Mipmaps
  63870. if (face === 5) {
  63871. engine.generateMipMapsForCubemap(this._texture);
  63872. }
  63873. }
  63874. }
  63875. else {
  63876. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  63877. // VBOs
  63878. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  63879. // Clear
  63880. engine.clear(scene.clearColor, true, true, true);
  63881. // Draw order
  63882. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  63883. }
  63884. // Unbind
  63885. engine.unBindFramebuffer(this._texture, this.isCube);
  63886. if (this.onGenerated) {
  63887. this.onGenerated();
  63888. }
  63889. };
  63890. ProceduralTexture.prototype.clone = function () {
  63891. var textureSize = this.getSize();
  63892. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  63893. // Base texture
  63894. newTexture.hasAlpha = this.hasAlpha;
  63895. newTexture.level = this.level;
  63896. // RenderTarget Texture
  63897. newTexture.coordinatesMode = this.coordinatesMode;
  63898. return newTexture;
  63899. };
  63900. ProceduralTexture.prototype.dispose = function () {
  63901. var scene = this.getScene();
  63902. if (!scene) {
  63903. return;
  63904. }
  63905. var index = scene._proceduralTextures.indexOf(this);
  63906. if (index >= 0) {
  63907. scene._proceduralTextures.splice(index, 1);
  63908. }
  63909. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63910. if (vertexBuffer) {
  63911. vertexBuffer.dispose();
  63912. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  63913. }
  63914. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  63915. this._indexBuffer = null;
  63916. }
  63917. _super.prototype.dispose.call(this);
  63918. };
  63919. return ProceduralTexture;
  63920. }(BABYLON.Texture));
  63921. BABYLON.ProceduralTexture = ProceduralTexture;
  63922. })(BABYLON || (BABYLON = {}));
  63923. //# sourceMappingURL=babylon.proceduralTexture.js.map
  63924. var BABYLON;
  63925. (function (BABYLON) {
  63926. var CustomProceduralTexture = /** @class */ (function (_super) {
  63927. __extends(CustomProceduralTexture, _super);
  63928. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  63929. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  63930. _this._animate = true;
  63931. _this._time = 0;
  63932. _this._texturePath = texturePath;
  63933. //Try to load json
  63934. _this.loadJson(texturePath);
  63935. _this.refreshRate = 1;
  63936. return _this;
  63937. }
  63938. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  63939. var _this = this;
  63940. var noConfigFile = function () {
  63941. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  63942. try {
  63943. _this.setFragment(_this._texturePath);
  63944. }
  63945. catch (ex) {
  63946. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  63947. }
  63948. };
  63949. var configFileUrl = jsonUrl + "/config.json";
  63950. var xhr = new XMLHttpRequest();
  63951. xhr.open("GET", configFileUrl, true);
  63952. xhr.addEventListener("load", function () {
  63953. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  63954. try {
  63955. _this._config = JSON.parse(xhr.response);
  63956. _this.updateShaderUniforms();
  63957. _this.updateTextures();
  63958. _this.setFragment(_this._texturePath + "/custom");
  63959. _this._animate = _this._config.animate;
  63960. _this.refreshRate = _this._config.refreshrate;
  63961. }
  63962. catch (ex) {
  63963. noConfigFile();
  63964. }
  63965. }
  63966. else {
  63967. noConfigFile();
  63968. }
  63969. }, false);
  63970. xhr.addEventListener("error", function () {
  63971. noConfigFile();
  63972. }, false);
  63973. try {
  63974. xhr.send();
  63975. }
  63976. catch (ex) {
  63977. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  63978. }
  63979. };
  63980. CustomProceduralTexture.prototype.isReady = function () {
  63981. if (!_super.prototype.isReady.call(this)) {
  63982. return false;
  63983. }
  63984. for (var name in this._textures) {
  63985. var texture = this._textures[name];
  63986. if (!texture.isReady()) {
  63987. return false;
  63988. }
  63989. }
  63990. return true;
  63991. };
  63992. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  63993. var scene = this.getScene();
  63994. if (this._animate && scene) {
  63995. this._time += scene.getAnimationRatio() * 0.03;
  63996. this.updateShaderUniforms();
  63997. }
  63998. _super.prototype.render.call(this, useCameraPostProcess);
  63999. };
  64000. CustomProceduralTexture.prototype.updateTextures = function () {
  64001. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  64002. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  64003. }
  64004. };
  64005. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  64006. if (this._config) {
  64007. for (var j = 0; j < this._config.uniforms.length; j++) {
  64008. var uniform = this._config.uniforms[j];
  64009. switch (uniform.type) {
  64010. case "float":
  64011. this.setFloat(uniform.name, uniform.value);
  64012. break;
  64013. case "color3":
  64014. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  64015. break;
  64016. case "color4":
  64017. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  64018. break;
  64019. case "vector2":
  64020. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  64021. break;
  64022. case "vector3":
  64023. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  64024. break;
  64025. }
  64026. }
  64027. }
  64028. this.setFloat("time", this._time);
  64029. };
  64030. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  64031. get: function () {
  64032. return this._animate;
  64033. },
  64034. set: function (value) {
  64035. this._animate = value;
  64036. },
  64037. enumerable: true,
  64038. configurable: true
  64039. });
  64040. return CustomProceduralTexture;
  64041. }(BABYLON.ProceduralTexture));
  64042. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  64043. })(BABYLON || (BABYLON = {}));
  64044. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  64045. var BABYLON;
  64046. (function (BABYLON) {
  64047. var FreeCameraGamepadInput = /** @class */ (function () {
  64048. function FreeCameraGamepadInput() {
  64049. this.gamepadAngularSensibility = 200;
  64050. this.gamepadMoveSensibility = 40;
  64051. // private members
  64052. this._cameraTransform = BABYLON.Matrix.Identity();
  64053. this._deltaTransform = BABYLON.Vector3.Zero();
  64054. this._vector3 = BABYLON.Vector3.Zero();
  64055. this._vector2 = BABYLON.Vector2.Zero();
  64056. }
  64057. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  64058. var _this = this;
  64059. var manager = this.camera.getScene().gamepadManager;
  64060. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  64061. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  64062. // prioritize XBOX gamepads.
  64063. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  64064. _this.gamepad = gamepad;
  64065. }
  64066. }
  64067. });
  64068. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  64069. if (_this.gamepad === gamepad) {
  64070. _this.gamepad = null;
  64071. }
  64072. });
  64073. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  64074. };
  64075. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  64076. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  64077. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  64078. this.gamepad = null;
  64079. };
  64080. FreeCameraGamepadInput.prototype.checkInputs = function () {
  64081. if (this.gamepad && this.gamepad.leftStick) {
  64082. var camera = this.camera;
  64083. var LSValues = this.gamepad.leftStick;
  64084. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  64085. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  64086. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  64087. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  64088. var RSValues = this.gamepad.rightStick;
  64089. if (RSValues) {
  64090. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  64091. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  64092. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  64093. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  64094. }
  64095. else {
  64096. RSValues = { x: 0, y: 0 };
  64097. }
  64098. if (!camera.rotationQuaternion) {
  64099. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  64100. }
  64101. else {
  64102. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  64103. }
  64104. var speed = camera._computeLocalCameraSpeed() * 50.0;
  64105. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  64106. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  64107. camera.cameraDirection.addInPlace(this._deltaTransform);
  64108. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  64109. camera.cameraRotation.addInPlace(this._vector2);
  64110. }
  64111. };
  64112. FreeCameraGamepadInput.prototype.getClassName = function () {
  64113. return "FreeCameraGamepadInput";
  64114. };
  64115. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  64116. return "gamepad";
  64117. };
  64118. __decorate([
  64119. BABYLON.serialize()
  64120. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  64121. __decorate([
  64122. BABYLON.serialize()
  64123. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  64124. return FreeCameraGamepadInput;
  64125. }());
  64126. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  64127. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  64128. })(BABYLON || (BABYLON = {}));
  64129. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  64130. var BABYLON;
  64131. (function (BABYLON) {
  64132. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  64133. function ArcRotateCameraGamepadInput() {
  64134. this.gamepadRotationSensibility = 80;
  64135. this.gamepadMoveSensibility = 40;
  64136. }
  64137. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  64138. var _this = this;
  64139. var manager = this.camera.getScene().gamepadManager;
  64140. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  64141. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  64142. // prioritize XBOX gamepads.
  64143. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  64144. _this.gamepad = gamepad;
  64145. }
  64146. }
  64147. });
  64148. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  64149. if (_this.gamepad === gamepad) {
  64150. _this.gamepad = null;
  64151. }
  64152. });
  64153. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  64154. };
  64155. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  64156. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  64157. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  64158. this.gamepad = null;
  64159. };
  64160. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  64161. if (this.gamepad) {
  64162. var camera = this.camera;
  64163. var RSValues = this.gamepad.rightStick;
  64164. if (RSValues) {
  64165. if (RSValues.x != 0) {
  64166. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  64167. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  64168. camera.inertialAlphaOffset += normalizedRX;
  64169. }
  64170. }
  64171. if (RSValues.y != 0) {
  64172. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  64173. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  64174. camera.inertialBetaOffset += normalizedRY;
  64175. }
  64176. }
  64177. }
  64178. var LSValues = this.gamepad.leftStick;
  64179. if (LSValues && LSValues.y != 0) {
  64180. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  64181. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  64182. this.camera.inertialRadiusOffset -= normalizedLY;
  64183. }
  64184. }
  64185. }
  64186. };
  64187. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  64188. return "ArcRotateCameraGamepadInput";
  64189. };
  64190. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  64191. return "gamepad";
  64192. };
  64193. __decorate([
  64194. BABYLON.serialize()
  64195. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  64196. __decorate([
  64197. BABYLON.serialize()
  64198. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  64199. return ArcRotateCameraGamepadInput;
  64200. }());
  64201. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  64202. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  64203. })(BABYLON || (BABYLON = {}));
  64204. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  64205. var BABYLON;
  64206. (function (BABYLON) {
  64207. var GamepadManager = /** @class */ (function () {
  64208. function GamepadManager(_scene) {
  64209. var _this = this;
  64210. this._scene = _scene;
  64211. this._babylonGamepads = [];
  64212. this._oneGamepadConnected = false;
  64213. this._isMonitoring = false;
  64214. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  64215. if (!BABYLON.Tools.IsWindowObjectExist()) {
  64216. this._gamepadEventSupported = false;
  64217. }
  64218. else {
  64219. this._gamepadEventSupported = 'GamepadEvent' in window;
  64220. this._gamepadSupport = (navigator.getGamepads ||
  64221. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  64222. }
  64223. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  64224. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  64225. for (var i in _this._babylonGamepads) {
  64226. var gamepad = _this._babylonGamepads[i];
  64227. if (gamepad && gamepad._isConnected) {
  64228. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  64229. }
  64230. }
  64231. });
  64232. this._onGamepadConnectedEvent = function (evt) {
  64233. var gamepad = evt.gamepad;
  64234. if (gamepad.index in _this._babylonGamepads) {
  64235. if (_this._babylonGamepads[gamepad.index].isConnected) {
  64236. return;
  64237. }
  64238. }
  64239. var newGamepad;
  64240. if (_this._babylonGamepads[gamepad.index]) {
  64241. newGamepad = _this._babylonGamepads[gamepad.index];
  64242. newGamepad.browserGamepad = gamepad;
  64243. newGamepad._isConnected = true;
  64244. }
  64245. else {
  64246. newGamepad = _this._addNewGamepad(gamepad);
  64247. }
  64248. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  64249. _this._startMonitoringGamepads();
  64250. };
  64251. this._onGamepadDisconnectedEvent = function (evt) {
  64252. var gamepad = evt.gamepad;
  64253. // Remove the gamepad from the list of gamepads to monitor.
  64254. for (var i in _this._babylonGamepads) {
  64255. if (_this._babylonGamepads[i].index === gamepad.index) {
  64256. var disconnectedGamepad = _this._babylonGamepads[i];
  64257. disconnectedGamepad._isConnected = false;
  64258. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  64259. break;
  64260. }
  64261. }
  64262. };
  64263. if (this._gamepadSupport) {
  64264. //first add already-connected gamepads
  64265. this._updateGamepadObjects();
  64266. if (this._babylonGamepads.length) {
  64267. this._startMonitoringGamepads();
  64268. }
  64269. // Checking if the gamepad connected event is supported (like in Firefox)
  64270. if (this._gamepadEventSupported) {
  64271. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  64272. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  64273. }
  64274. else {
  64275. this._startMonitoringGamepads();
  64276. }
  64277. }
  64278. }
  64279. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  64280. get: function () {
  64281. return this._babylonGamepads;
  64282. },
  64283. enumerable: true,
  64284. configurable: true
  64285. });
  64286. GamepadManager.prototype.getGamepadByType = function (type) {
  64287. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  64288. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  64289. var gamepad = _a[_i];
  64290. if (gamepad && gamepad.type === type) {
  64291. return gamepad;
  64292. }
  64293. }
  64294. return null;
  64295. };
  64296. GamepadManager.prototype.dispose = function () {
  64297. if (this._gamepadEventSupported) {
  64298. if (this._onGamepadConnectedEvent) {
  64299. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  64300. }
  64301. if (this._onGamepadDisconnectedEvent) {
  64302. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  64303. }
  64304. this._onGamepadConnectedEvent = null;
  64305. this._onGamepadDisconnectedEvent = null;
  64306. }
  64307. this._babylonGamepads.forEach(function (gamepad) {
  64308. gamepad.dispose();
  64309. });
  64310. this.onGamepadConnectedObservable.clear();
  64311. this.onGamepadDisconnectedObservable.clear();
  64312. this._oneGamepadConnected = false;
  64313. this._stopMonitoringGamepads();
  64314. this._babylonGamepads = [];
  64315. };
  64316. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  64317. if (!this._oneGamepadConnected) {
  64318. this._oneGamepadConnected = true;
  64319. }
  64320. var newGamepad;
  64321. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  64322. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  64323. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  64324. }
  64325. else if (gamepad.pose) {
  64326. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  64327. }
  64328. else {
  64329. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  64330. }
  64331. this._babylonGamepads[newGamepad.index] = newGamepad;
  64332. return newGamepad;
  64333. };
  64334. GamepadManager.prototype._startMonitoringGamepads = function () {
  64335. if (!this._isMonitoring) {
  64336. this._isMonitoring = true;
  64337. //back-comp
  64338. if (!this._scene) {
  64339. this._checkGamepadsStatus();
  64340. }
  64341. }
  64342. };
  64343. GamepadManager.prototype._stopMonitoringGamepads = function () {
  64344. this._isMonitoring = false;
  64345. };
  64346. GamepadManager.prototype._checkGamepadsStatus = function () {
  64347. var _this = this;
  64348. // Hack to be compatible Chrome
  64349. this._updateGamepadObjects();
  64350. for (var i in this._babylonGamepads) {
  64351. var gamepad = this._babylonGamepads[i];
  64352. if (!gamepad || !gamepad.isConnected) {
  64353. continue;
  64354. }
  64355. gamepad.update();
  64356. }
  64357. if (this._isMonitoring && !this._scene) {
  64358. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  64359. }
  64360. };
  64361. // This function is called only on Chrome, which does not properly support
  64362. // connection/disconnection events and forces you to recopy again the gamepad object
  64363. GamepadManager.prototype._updateGamepadObjects = function () {
  64364. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  64365. for (var i = 0; i < gamepads.length; i++) {
  64366. if (gamepads[i]) {
  64367. if (!this._babylonGamepads[gamepads[i].index]) {
  64368. var newGamepad = this._addNewGamepad(gamepads[i]);
  64369. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  64370. }
  64371. else {
  64372. // Forced to copy again this object for Chrome for unknown reason
  64373. this._babylonGamepads[i].browserGamepad = gamepads[i];
  64374. if (!this._babylonGamepads[i].isConnected) {
  64375. this._babylonGamepads[i]._isConnected = true;
  64376. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  64377. }
  64378. }
  64379. }
  64380. }
  64381. };
  64382. return GamepadManager;
  64383. }());
  64384. BABYLON.GamepadManager = GamepadManager;
  64385. })(BABYLON || (BABYLON = {}));
  64386. //# sourceMappingURL=babylon.gamepadManager.js.map
  64387. var BABYLON;
  64388. (function (BABYLON) {
  64389. var StickValues = /** @class */ (function () {
  64390. function StickValues(x, y) {
  64391. this.x = x;
  64392. this.y = y;
  64393. }
  64394. return StickValues;
  64395. }());
  64396. BABYLON.StickValues = StickValues;
  64397. var Gamepad = /** @class */ (function () {
  64398. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  64399. if (leftStickX === void 0) { leftStickX = 0; }
  64400. if (leftStickY === void 0) { leftStickY = 1; }
  64401. if (rightStickX === void 0) { rightStickX = 2; }
  64402. if (rightStickY === void 0) { rightStickY = 3; }
  64403. this.id = id;
  64404. this.index = index;
  64405. this.browserGamepad = browserGamepad;
  64406. this._isConnected = true;
  64407. this._invertLeftStickY = false;
  64408. this.type = Gamepad.GAMEPAD;
  64409. this._leftStickAxisX = leftStickX;
  64410. this._leftStickAxisY = leftStickY;
  64411. this._rightStickAxisX = rightStickX;
  64412. this._rightStickAxisY = rightStickY;
  64413. if (this.browserGamepad.axes.length >= 2) {
  64414. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  64415. }
  64416. if (this.browserGamepad.axes.length >= 4) {
  64417. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  64418. }
  64419. }
  64420. Object.defineProperty(Gamepad.prototype, "isConnected", {
  64421. get: function () {
  64422. return this._isConnected;
  64423. },
  64424. enumerable: true,
  64425. configurable: true
  64426. });
  64427. Gamepad.prototype.onleftstickchanged = function (callback) {
  64428. this._onleftstickchanged = callback;
  64429. };
  64430. Gamepad.prototype.onrightstickchanged = function (callback) {
  64431. this._onrightstickchanged = callback;
  64432. };
  64433. Object.defineProperty(Gamepad.prototype, "leftStick", {
  64434. get: function () {
  64435. return this._leftStick;
  64436. },
  64437. set: function (newValues) {
  64438. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  64439. this._onleftstickchanged(newValues);
  64440. }
  64441. this._leftStick = newValues;
  64442. },
  64443. enumerable: true,
  64444. configurable: true
  64445. });
  64446. Object.defineProperty(Gamepad.prototype, "rightStick", {
  64447. get: function () {
  64448. return this._rightStick;
  64449. },
  64450. set: function (newValues) {
  64451. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  64452. this._onrightstickchanged(newValues);
  64453. }
  64454. this._rightStick = newValues;
  64455. },
  64456. enumerable: true,
  64457. configurable: true
  64458. });
  64459. Gamepad.prototype.update = function () {
  64460. if (this._leftStick) {
  64461. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  64462. if (this._invertLeftStickY) {
  64463. this.leftStick.y *= -1;
  64464. }
  64465. }
  64466. if (this._rightStick) {
  64467. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  64468. }
  64469. };
  64470. Gamepad.prototype.dispose = function () {
  64471. };
  64472. Gamepad.GAMEPAD = 0;
  64473. Gamepad.GENERIC = 1;
  64474. Gamepad.XBOX = 2;
  64475. Gamepad.POSE_ENABLED = 3;
  64476. return Gamepad;
  64477. }());
  64478. BABYLON.Gamepad = Gamepad;
  64479. var GenericPad = /** @class */ (function (_super) {
  64480. __extends(GenericPad, _super);
  64481. function GenericPad(id, index, browserGamepad) {
  64482. var _this = _super.call(this, id, index, browserGamepad) || this;
  64483. _this.onButtonDownObservable = new BABYLON.Observable();
  64484. _this.onButtonUpObservable = new BABYLON.Observable();
  64485. _this.type = Gamepad.GENERIC;
  64486. _this._buttons = new Array(browserGamepad.buttons.length);
  64487. return _this;
  64488. }
  64489. GenericPad.prototype.onbuttondown = function (callback) {
  64490. this._onbuttondown = callback;
  64491. };
  64492. GenericPad.prototype.onbuttonup = function (callback) {
  64493. this._onbuttonup = callback;
  64494. };
  64495. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  64496. if (newValue !== currentValue) {
  64497. if (newValue === 1) {
  64498. if (this._onbuttondown) {
  64499. this._onbuttondown(buttonIndex);
  64500. }
  64501. this.onButtonDownObservable.notifyObservers(buttonIndex);
  64502. }
  64503. if (newValue === 0) {
  64504. if (this._onbuttonup) {
  64505. this._onbuttonup(buttonIndex);
  64506. }
  64507. this.onButtonUpObservable.notifyObservers(buttonIndex);
  64508. }
  64509. }
  64510. return newValue;
  64511. };
  64512. GenericPad.prototype.update = function () {
  64513. _super.prototype.update.call(this);
  64514. for (var index = 0; index < this._buttons.length; index++) {
  64515. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  64516. }
  64517. };
  64518. GenericPad.prototype.dispose = function () {
  64519. _super.prototype.dispose.call(this);
  64520. this.onButtonDownObservable.clear();
  64521. this.onButtonUpObservable.clear();
  64522. };
  64523. return GenericPad;
  64524. }(Gamepad));
  64525. BABYLON.GenericPad = GenericPad;
  64526. })(BABYLON || (BABYLON = {}));
  64527. //# sourceMappingURL=babylon.gamepad.js.map
  64528. var BABYLON;
  64529. (function (BABYLON) {
  64530. var Xbox360Button;
  64531. (function (Xbox360Button) {
  64532. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  64533. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  64534. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  64535. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  64536. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  64537. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  64538. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  64539. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  64540. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  64541. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  64542. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  64543. var Xbox360Dpad;
  64544. (function (Xbox360Dpad) {
  64545. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  64546. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  64547. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  64548. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  64549. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  64550. var Xbox360Pad = /** @class */ (function (_super) {
  64551. __extends(Xbox360Pad, _super);
  64552. function Xbox360Pad(id, index, gamepad, xboxOne) {
  64553. if (xboxOne === void 0) { xboxOne = false; }
  64554. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  64555. _this._leftTrigger = 0;
  64556. _this._rightTrigger = 0;
  64557. _this.onButtonDownObservable = new BABYLON.Observable();
  64558. _this.onButtonUpObservable = new BABYLON.Observable();
  64559. _this.onPadDownObservable = new BABYLON.Observable();
  64560. _this.onPadUpObservable = new BABYLON.Observable();
  64561. _this._buttonA = 0;
  64562. _this._buttonB = 0;
  64563. _this._buttonX = 0;
  64564. _this._buttonY = 0;
  64565. _this._buttonBack = 0;
  64566. _this._buttonStart = 0;
  64567. _this._buttonLB = 0;
  64568. _this._buttonRB = 0;
  64569. _this._buttonLeftStick = 0;
  64570. _this._buttonRightStick = 0;
  64571. _this._dPadUp = 0;
  64572. _this._dPadDown = 0;
  64573. _this._dPadLeft = 0;
  64574. _this._dPadRight = 0;
  64575. _this._isXboxOnePad = false;
  64576. _this.type = BABYLON.Gamepad.XBOX;
  64577. _this._isXboxOnePad = xboxOne;
  64578. return _this;
  64579. }
  64580. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  64581. this._onlefttriggerchanged = callback;
  64582. };
  64583. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  64584. this._onrighttriggerchanged = callback;
  64585. };
  64586. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  64587. get: function () {
  64588. return this._leftTrigger;
  64589. },
  64590. set: function (newValue) {
  64591. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  64592. this._onlefttriggerchanged(newValue);
  64593. }
  64594. this._leftTrigger = newValue;
  64595. },
  64596. enumerable: true,
  64597. configurable: true
  64598. });
  64599. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  64600. get: function () {
  64601. return this._rightTrigger;
  64602. },
  64603. set: function (newValue) {
  64604. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  64605. this._onrighttriggerchanged(newValue);
  64606. }
  64607. this._rightTrigger = newValue;
  64608. },
  64609. enumerable: true,
  64610. configurable: true
  64611. });
  64612. Xbox360Pad.prototype.onbuttondown = function (callback) {
  64613. this._onbuttondown = callback;
  64614. };
  64615. Xbox360Pad.prototype.onbuttonup = function (callback) {
  64616. this._onbuttonup = callback;
  64617. };
  64618. Xbox360Pad.prototype.ondpaddown = function (callback) {
  64619. this._ondpaddown = callback;
  64620. };
  64621. Xbox360Pad.prototype.ondpadup = function (callback) {
  64622. this._ondpadup = callback;
  64623. };
  64624. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  64625. if (newValue !== currentValue) {
  64626. if (newValue === 1) {
  64627. if (this._onbuttondown) {
  64628. this._onbuttondown(buttonType);
  64629. }
  64630. this.onButtonDownObservable.notifyObservers(buttonType);
  64631. }
  64632. if (newValue === 0) {
  64633. if (this._onbuttonup) {
  64634. this._onbuttonup(buttonType);
  64635. }
  64636. this.onButtonUpObservable.notifyObservers(buttonType);
  64637. }
  64638. }
  64639. return newValue;
  64640. };
  64641. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  64642. if (newValue !== currentValue) {
  64643. if (newValue === 1) {
  64644. if (this._ondpaddown) {
  64645. this._ondpaddown(buttonType);
  64646. }
  64647. this.onPadDownObservable.notifyObservers(buttonType);
  64648. }
  64649. if (newValue === 0) {
  64650. if (this._ondpadup) {
  64651. this._ondpadup(buttonType);
  64652. }
  64653. this.onPadUpObservable.notifyObservers(buttonType);
  64654. }
  64655. }
  64656. return newValue;
  64657. };
  64658. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  64659. get: function () {
  64660. return this._buttonA;
  64661. },
  64662. set: function (value) {
  64663. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  64664. },
  64665. enumerable: true,
  64666. configurable: true
  64667. });
  64668. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  64669. get: function () {
  64670. return this._buttonB;
  64671. },
  64672. set: function (value) {
  64673. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  64674. },
  64675. enumerable: true,
  64676. configurable: true
  64677. });
  64678. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  64679. get: function () {
  64680. return this._buttonX;
  64681. },
  64682. set: function (value) {
  64683. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  64684. },
  64685. enumerable: true,
  64686. configurable: true
  64687. });
  64688. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  64689. get: function () {
  64690. return this._buttonY;
  64691. },
  64692. set: function (value) {
  64693. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  64694. },
  64695. enumerable: true,
  64696. configurable: true
  64697. });
  64698. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  64699. get: function () {
  64700. return this._buttonStart;
  64701. },
  64702. set: function (value) {
  64703. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  64704. },
  64705. enumerable: true,
  64706. configurable: true
  64707. });
  64708. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  64709. get: function () {
  64710. return this._buttonBack;
  64711. },
  64712. set: function (value) {
  64713. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  64714. },
  64715. enumerable: true,
  64716. configurable: true
  64717. });
  64718. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  64719. get: function () {
  64720. return this._buttonLB;
  64721. },
  64722. set: function (value) {
  64723. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  64724. },
  64725. enumerable: true,
  64726. configurable: true
  64727. });
  64728. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  64729. get: function () {
  64730. return this._buttonRB;
  64731. },
  64732. set: function (value) {
  64733. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  64734. },
  64735. enumerable: true,
  64736. configurable: true
  64737. });
  64738. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  64739. get: function () {
  64740. return this._buttonLeftStick;
  64741. },
  64742. set: function (value) {
  64743. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  64744. },
  64745. enumerable: true,
  64746. configurable: true
  64747. });
  64748. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  64749. get: function () {
  64750. return this._buttonRightStick;
  64751. },
  64752. set: function (value) {
  64753. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  64754. },
  64755. enumerable: true,
  64756. configurable: true
  64757. });
  64758. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  64759. get: function () {
  64760. return this._dPadUp;
  64761. },
  64762. set: function (value) {
  64763. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  64764. },
  64765. enumerable: true,
  64766. configurable: true
  64767. });
  64768. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  64769. get: function () {
  64770. return this._dPadDown;
  64771. },
  64772. set: function (value) {
  64773. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  64774. },
  64775. enumerable: true,
  64776. configurable: true
  64777. });
  64778. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  64779. get: function () {
  64780. return this._dPadLeft;
  64781. },
  64782. set: function (value) {
  64783. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  64784. },
  64785. enumerable: true,
  64786. configurable: true
  64787. });
  64788. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  64789. get: function () {
  64790. return this._dPadRight;
  64791. },
  64792. set: function (value) {
  64793. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  64794. },
  64795. enumerable: true,
  64796. configurable: true
  64797. });
  64798. Xbox360Pad.prototype.update = function () {
  64799. _super.prototype.update.call(this);
  64800. if (this._isXboxOnePad) {
  64801. this.buttonA = this.browserGamepad.buttons[0].value;
  64802. this.buttonB = this.browserGamepad.buttons[1].value;
  64803. this.buttonX = this.browserGamepad.buttons[2].value;
  64804. this.buttonY = this.browserGamepad.buttons[3].value;
  64805. this.buttonLB = this.browserGamepad.buttons[4].value;
  64806. this.buttonRB = this.browserGamepad.buttons[5].value;
  64807. this.leftTrigger = this.browserGamepad.axes[2];
  64808. this.rightTrigger = this.browserGamepad.axes[5];
  64809. this.buttonBack = this.browserGamepad.buttons[9].value;
  64810. this.buttonStart = this.browserGamepad.buttons[8].value;
  64811. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  64812. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  64813. this.dPadUp = this.browserGamepad.buttons[11].value;
  64814. this.dPadDown = this.browserGamepad.buttons[12].value;
  64815. this.dPadLeft = this.browserGamepad.buttons[13].value;
  64816. this.dPadRight = this.browserGamepad.buttons[14].value;
  64817. }
  64818. else {
  64819. this.buttonA = this.browserGamepad.buttons[0].value;
  64820. this.buttonB = this.browserGamepad.buttons[1].value;
  64821. this.buttonX = this.browserGamepad.buttons[2].value;
  64822. this.buttonY = this.browserGamepad.buttons[3].value;
  64823. this.buttonLB = this.browserGamepad.buttons[4].value;
  64824. this.buttonRB = this.browserGamepad.buttons[5].value;
  64825. this.leftTrigger = this.browserGamepad.buttons[6].value;
  64826. this.rightTrigger = this.browserGamepad.buttons[7].value;
  64827. this.buttonBack = this.browserGamepad.buttons[8].value;
  64828. this.buttonStart = this.browserGamepad.buttons[9].value;
  64829. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  64830. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  64831. this.dPadUp = this.browserGamepad.buttons[12].value;
  64832. this.dPadDown = this.browserGamepad.buttons[13].value;
  64833. this.dPadLeft = this.browserGamepad.buttons[14].value;
  64834. this.dPadRight = this.browserGamepad.buttons[15].value;
  64835. }
  64836. };
  64837. Xbox360Pad.prototype.dispose = function () {
  64838. _super.prototype.dispose.call(this);
  64839. this.onButtonDownObservable.clear();
  64840. this.onButtonUpObservable.clear();
  64841. this.onPadDownObservable.clear();
  64842. this.onPadUpObservable.clear();
  64843. };
  64844. return Xbox360Pad;
  64845. }(BABYLON.Gamepad));
  64846. BABYLON.Xbox360Pad = Xbox360Pad;
  64847. })(BABYLON || (BABYLON = {}));
  64848. //# sourceMappingURL=babylon.xboxGamepad.js.map
  64849. var BABYLON;
  64850. (function (BABYLON) {
  64851. var PoseEnabledControllerType;
  64852. (function (PoseEnabledControllerType) {
  64853. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  64854. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  64855. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  64856. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  64857. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  64858. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  64859. var PoseEnabledControllerHelper = /** @class */ (function () {
  64860. function PoseEnabledControllerHelper() {
  64861. }
  64862. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  64863. // Oculus Touch
  64864. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  64865. return new BABYLON.OculusTouchController(vrGamepad);
  64866. }
  64867. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  64868. return new BABYLON.WindowsMotionController(vrGamepad);
  64869. }
  64870. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  64871. return new BABYLON.ViveController(vrGamepad);
  64872. }
  64873. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  64874. return new BABYLON.GearVRController(vrGamepad);
  64875. }
  64876. else {
  64877. return new BABYLON.GenericController(vrGamepad);
  64878. }
  64879. };
  64880. return PoseEnabledControllerHelper;
  64881. }());
  64882. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  64883. var PoseEnabledController = /** @class */ (function (_super) {
  64884. __extends(PoseEnabledController, _super);
  64885. function PoseEnabledController(browserGamepad) {
  64886. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  64887. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  64888. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  64889. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  64890. // Represents device position and rotation in babylon space
  64891. _this.devicePosition = BABYLON.Vector3.Zero();
  64892. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  64893. _this.deviceScaleFactor = 1;
  64894. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  64895. _this._deviceToWorld = BABYLON.Matrix.Identity();
  64896. _this._workingMatrix = BABYLON.Matrix.Identity();
  64897. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  64898. _this.controllerType = PoseEnabledControllerType.GENERIC;
  64899. _this.position = BABYLON.Vector3.Zero();
  64900. _this.rotationQuaternion = new BABYLON.Quaternion();
  64901. _this._calculatedPosition = BABYLON.Vector3.Zero();
  64902. _this._calculatedRotation = new BABYLON.Quaternion();
  64903. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  64904. return _this;
  64905. }
  64906. PoseEnabledController.prototype.update = function () {
  64907. _super.prototype.update.call(this);
  64908. var pose = this.browserGamepad.pose;
  64909. this.updateFromDevice(pose);
  64910. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  64911. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  64912. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  64913. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  64914. if (this._mesh) {
  64915. this._mesh.position.copyFrom(this.devicePosition);
  64916. if (this._mesh.rotationQuaternion) {
  64917. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  64918. }
  64919. }
  64920. };
  64921. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  64922. if (poseData) {
  64923. this.rawPose = poseData;
  64924. if (poseData.position) {
  64925. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  64926. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  64927. this._deviceRoomPosition.z *= -1;
  64928. }
  64929. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  64930. this._calculatedPosition.addInPlace(this.position);
  64931. }
  64932. var pose = this.rawPose;
  64933. if (poseData.orientation && pose.orientation) {
  64934. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  64935. if (this._mesh) {
  64936. if (this._mesh.getScene().useRightHandedSystem) {
  64937. this._deviceRoomRotationQuaternion.z *= -1;
  64938. this._deviceRoomRotationQuaternion.w *= -1;
  64939. }
  64940. else {
  64941. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  64942. }
  64943. }
  64944. // if the camera is set, rotate to the camera's rotation
  64945. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  64946. }
  64947. }
  64948. };
  64949. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  64950. if (this._mesh) {
  64951. this._mesh.parent = null;
  64952. }
  64953. this._mesh = mesh;
  64954. if (this._poseControlledCamera) {
  64955. this._mesh.parent = this._poseControlledCamera;
  64956. }
  64957. if (!this._mesh.rotationQuaternion) {
  64958. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  64959. }
  64960. };
  64961. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  64962. this._poseControlledCamera = camera;
  64963. if (this._mesh) {
  64964. this._mesh.parent = this._poseControlledCamera;
  64965. }
  64966. };
  64967. PoseEnabledController.prototype.dispose = function () {
  64968. if (this._mesh) {
  64969. this._mesh.dispose();
  64970. }
  64971. this._mesh = null;
  64972. _super.prototype.dispose.call(this);
  64973. };
  64974. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  64975. get: function () {
  64976. return this._mesh;
  64977. },
  64978. enumerable: true,
  64979. configurable: true
  64980. });
  64981. PoseEnabledController.prototype.getForwardRay = function (length) {
  64982. if (length === void 0) { length = 100; }
  64983. if (!this.mesh) {
  64984. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  64985. }
  64986. var m = this.mesh.getWorldMatrix();
  64987. var origin = m.getTranslation();
  64988. var forward = new BABYLON.Vector3(0, 0, -1);
  64989. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  64990. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  64991. return new BABYLON.Ray(origin, direction, length);
  64992. };
  64993. return PoseEnabledController;
  64994. }(BABYLON.Gamepad));
  64995. BABYLON.PoseEnabledController = PoseEnabledController;
  64996. })(BABYLON || (BABYLON = {}));
  64997. //# sourceMappingURL=babylon.poseEnabledController.js.map
  64998. var BABYLON;
  64999. (function (BABYLON) {
  65000. var WebVRController = /** @class */ (function (_super) {
  65001. __extends(WebVRController, _super);
  65002. function WebVRController(vrGamepad) {
  65003. var _this = _super.call(this, vrGamepad) || this;
  65004. // Observables
  65005. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  65006. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  65007. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  65008. _this.onPadStateChangedObservable = new BABYLON.Observable();
  65009. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  65010. _this.pad = { x: 0, y: 0 };
  65011. // avoid GC, store state in a tmp object
  65012. _this._changes = {
  65013. pressChanged: false,
  65014. touchChanged: false,
  65015. valueChanged: false,
  65016. changed: false
  65017. };
  65018. _this._buttons = new Array(vrGamepad.buttons.length);
  65019. _this.hand = vrGamepad.hand;
  65020. return _this;
  65021. }
  65022. WebVRController.prototype.onButtonStateChange = function (callback) {
  65023. this._onButtonStateChange = callback;
  65024. };
  65025. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  65026. get: function () {
  65027. return this._defaultModel;
  65028. },
  65029. enumerable: true,
  65030. configurable: true
  65031. });
  65032. WebVRController.prototype.update = function () {
  65033. _super.prototype.update.call(this);
  65034. for (var index = 0; index < this._buttons.length; index++) {
  65035. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  65036. }
  65037. ;
  65038. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  65039. this.pad.x = this.leftStick.x;
  65040. this.pad.y = this.leftStick.y;
  65041. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  65042. }
  65043. };
  65044. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  65045. if (!newState) {
  65046. newState = {
  65047. pressed: false,
  65048. touched: false,
  65049. value: 0
  65050. };
  65051. }
  65052. if (!currentState) {
  65053. this._buttons[buttonIndex] = {
  65054. pressed: newState.pressed,
  65055. touched: newState.touched,
  65056. value: newState.value
  65057. };
  65058. return;
  65059. }
  65060. this._checkChanges(newState, currentState);
  65061. if (this._changes.changed) {
  65062. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  65063. this.handleButtonChange(buttonIndex, newState, this._changes);
  65064. }
  65065. this._buttons[buttonIndex].pressed = newState.pressed;
  65066. this._buttons[buttonIndex].touched = newState.touched;
  65067. // oculus triggers are never 0, thou not touched.
  65068. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  65069. };
  65070. WebVRController.prototype._checkChanges = function (newState, currentState) {
  65071. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  65072. this._changes.touchChanged = newState.touched !== currentState.touched;
  65073. this._changes.valueChanged = newState.value !== currentState.value;
  65074. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  65075. return this._changes;
  65076. };
  65077. WebVRController.prototype.dispose = function () {
  65078. _super.prototype.dispose.call(this);
  65079. this.onTriggerStateChangedObservable.clear();
  65080. this.onMainButtonStateChangedObservable.clear();
  65081. this.onSecondaryButtonStateChangedObservable.clear();
  65082. this.onPadStateChangedObservable.clear();
  65083. this.onPadValuesChangedObservable.clear();
  65084. };
  65085. return WebVRController;
  65086. }(BABYLON.PoseEnabledController));
  65087. BABYLON.WebVRController = WebVRController;
  65088. })(BABYLON || (BABYLON = {}));
  65089. //# sourceMappingURL=babylon.webVRController.js.map
  65090. var BABYLON;
  65091. (function (BABYLON) {
  65092. var OculusTouchController = /** @class */ (function (_super) {
  65093. __extends(OculusTouchController, _super);
  65094. function OculusTouchController(vrGamepad) {
  65095. var _this = _super.call(this, vrGamepad) || this;
  65096. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  65097. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  65098. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  65099. return _this;
  65100. }
  65101. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65102. var _this = this;
  65103. var meshName;
  65104. // Hand
  65105. if (this.hand === 'left') {
  65106. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  65107. }
  65108. else {
  65109. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  65110. }
  65111. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  65112. /*
  65113. Parent Mesh name: oculus_touch_left
  65114. - body
  65115. - trigger
  65116. - thumbstick
  65117. - grip
  65118. - button_y
  65119. - button_x
  65120. - button_enter
  65121. */
  65122. _this._defaultModel = newMeshes[1];
  65123. _this.attachToMesh(_this._defaultModel);
  65124. if (meshLoaded) {
  65125. meshLoaded(_this._defaultModel);
  65126. }
  65127. });
  65128. };
  65129. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  65130. // helper getters for left and right hand.
  65131. get: function () {
  65132. if (this.hand === 'right') {
  65133. return this.onMainButtonStateChangedObservable;
  65134. }
  65135. else {
  65136. throw new Error('No A button on left hand');
  65137. }
  65138. },
  65139. enumerable: true,
  65140. configurable: true
  65141. });
  65142. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  65143. get: function () {
  65144. if (this.hand === 'right') {
  65145. return this.onSecondaryButtonStateChangedObservable;
  65146. }
  65147. else {
  65148. throw new Error('No B button on left hand');
  65149. }
  65150. },
  65151. enumerable: true,
  65152. configurable: true
  65153. });
  65154. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  65155. get: function () {
  65156. if (this.hand === 'left') {
  65157. return this.onMainButtonStateChangedObservable;
  65158. }
  65159. else {
  65160. throw new Error('No X button on right hand');
  65161. }
  65162. },
  65163. enumerable: true,
  65164. configurable: true
  65165. });
  65166. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  65167. get: function () {
  65168. if (this.hand === 'left') {
  65169. return this.onSecondaryButtonStateChangedObservable;
  65170. }
  65171. else {
  65172. throw new Error('No Y button on right hand');
  65173. }
  65174. },
  65175. enumerable: true,
  65176. configurable: true
  65177. });
  65178. /*
  65179. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  65180. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  65181. 2) secondary trigger (same)
  65182. 3) A (right) X (left), touch, pressed = value
  65183. 4) B / Y
  65184. 5) thumb rest
  65185. */
  65186. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  65187. var notifyObject = state; //{ state: state, changes: changes };
  65188. var triggerDirection = this.hand === 'right' ? -1 : 1;
  65189. switch (buttonIdx) {
  65190. case 0:
  65191. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  65192. return;
  65193. case 1:// index trigger
  65194. if (this._defaultModel) {
  65195. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  65196. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  65197. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  65198. }
  65199. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  65200. return;
  65201. case 2:// secondary trigger
  65202. if (this._defaultModel) {
  65203. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  65204. }
  65205. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  65206. return;
  65207. case 3:
  65208. if (this._defaultModel) {
  65209. if (notifyObject.pressed) {
  65210. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  65211. }
  65212. else {
  65213. (this._defaultModel.getChildren()[1]).position.y = 0;
  65214. }
  65215. }
  65216. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  65217. return;
  65218. case 4:
  65219. if (this._defaultModel) {
  65220. if (notifyObject.pressed) {
  65221. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  65222. }
  65223. else {
  65224. (this._defaultModel.getChildren()[2]).position.y = 0;
  65225. }
  65226. }
  65227. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  65228. return;
  65229. case 5:
  65230. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  65231. return;
  65232. }
  65233. };
  65234. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  65235. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  65236. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  65237. return OculusTouchController;
  65238. }(BABYLON.WebVRController));
  65239. BABYLON.OculusTouchController = OculusTouchController;
  65240. })(BABYLON || (BABYLON = {}));
  65241. //# sourceMappingURL=babylon.oculusTouchController.js.map
  65242. var BABYLON;
  65243. (function (BABYLON) {
  65244. var ViveController = /** @class */ (function (_super) {
  65245. __extends(ViveController, _super);
  65246. function ViveController(vrGamepad) {
  65247. var _this = _super.call(this, vrGamepad) || this;
  65248. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  65249. _this._invertLeftStickY = true;
  65250. return _this;
  65251. }
  65252. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65253. var _this = this;
  65254. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  65255. /*
  65256. Parent Mesh name: ViveWand
  65257. - body
  65258. - r_gripper
  65259. - l_gripper
  65260. - menu_button
  65261. - system_button
  65262. - trackpad
  65263. - trigger
  65264. - LED
  65265. */
  65266. _this._defaultModel = newMeshes[1];
  65267. _this.attachToMesh(_this._defaultModel);
  65268. if (meshLoaded) {
  65269. meshLoaded(_this._defaultModel);
  65270. }
  65271. });
  65272. };
  65273. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  65274. get: function () {
  65275. return this.onMainButtonStateChangedObservable;
  65276. },
  65277. enumerable: true,
  65278. configurable: true
  65279. });
  65280. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  65281. get: function () {
  65282. return this.onMainButtonStateChangedObservable;
  65283. },
  65284. enumerable: true,
  65285. configurable: true
  65286. });
  65287. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  65288. get: function () {
  65289. return this.onSecondaryButtonStateChangedObservable;
  65290. },
  65291. enumerable: true,
  65292. configurable: true
  65293. });
  65294. /**
  65295. * Vive mapping:
  65296. * 0: touchpad
  65297. * 1: trigger
  65298. * 2: left AND right buttons
  65299. * 3: menu button
  65300. */
  65301. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  65302. var notifyObject = state; //{ state: state, changes: changes };
  65303. switch (buttonIdx) {
  65304. case 0:
  65305. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  65306. return;
  65307. case 1:// index trigger
  65308. if (this._defaultModel) {
  65309. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  65310. }
  65311. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  65312. return;
  65313. case 2:// left AND right button
  65314. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  65315. return;
  65316. case 3:
  65317. if (this._defaultModel) {
  65318. if (notifyObject.pressed) {
  65319. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  65320. }
  65321. else {
  65322. (this._defaultModel.getChildren()[2]).position.y = 0;
  65323. }
  65324. }
  65325. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  65326. return;
  65327. }
  65328. };
  65329. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  65330. ViveController.MODEL_FILENAME = 'wand.babylon';
  65331. return ViveController;
  65332. }(BABYLON.WebVRController));
  65333. BABYLON.ViveController = ViveController;
  65334. })(BABYLON || (BABYLON = {}));
  65335. //# sourceMappingURL=babylon.viveController.js.map
  65336. var BABYLON;
  65337. (function (BABYLON) {
  65338. var GenericController = /** @class */ (function (_super) {
  65339. __extends(GenericController, _super);
  65340. function GenericController(vrGamepad) {
  65341. return _super.call(this, vrGamepad) || this;
  65342. }
  65343. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65344. var _this = this;
  65345. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  65346. _this._defaultModel = newMeshes[1];
  65347. _this.attachToMesh(_this._defaultModel);
  65348. if (meshLoaded) {
  65349. meshLoaded(_this._defaultModel);
  65350. }
  65351. });
  65352. };
  65353. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  65354. console.log("Button id: " + buttonIdx + "state: ");
  65355. console.dir(state);
  65356. };
  65357. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65358. GenericController.MODEL_FILENAME = 'generic.babylon';
  65359. return GenericController;
  65360. }(BABYLON.WebVRController));
  65361. BABYLON.GenericController = GenericController;
  65362. })(BABYLON || (BABYLON = {}));
  65363. //# sourceMappingURL=babylon.genericController.js.map
  65364. var BABYLON;
  65365. (function (BABYLON) {
  65366. var LoadedMeshInfo = /** @class */ (function () {
  65367. function LoadedMeshInfo() {
  65368. this.buttonMeshes = {};
  65369. this.axisMeshes = {};
  65370. }
  65371. return LoadedMeshInfo;
  65372. }());
  65373. var WindowsMotionController = /** @class */ (function (_super) {
  65374. __extends(WindowsMotionController, _super);
  65375. function WindowsMotionController(vrGamepad) {
  65376. var _this = _super.call(this, vrGamepad) || this;
  65377. _this._mapping = {
  65378. // Semantic button names
  65379. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  65380. // A mapping of the button name to glTF model node name
  65381. // that should be transformed by button value.
  65382. buttonMeshNames: {
  65383. 'trigger': 'SELECT',
  65384. 'menu': 'MENU',
  65385. 'grip': 'GRASP',
  65386. 'thumbstick': 'THUMBSTICK_PRESS',
  65387. 'trackpad': 'TOUCHPAD_PRESS'
  65388. },
  65389. // This mapping is used to translate from the Motion Controller to Babylon semantics
  65390. buttonObservableNames: {
  65391. 'trigger': 'onTriggerStateChangedObservable',
  65392. 'menu': 'onSecondaryButtonStateChangedObservable',
  65393. 'grip': 'onMainButtonStateChangedObservable',
  65394. 'thumbstick': 'onPadStateChangedObservable',
  65395. 'trackpad': 'onTrackpadChangedObservable'
  65396. },
  65397. // A mapping of the axis name to glTF model node name
  65398. // that should be transformed by axis value.
  65399. // This array mirrors the browserGamepad.axes array, such that
  65400. // the mesh corresponding to axis 0 is in this array index 0.
  65401. axisMeshNames: [
  65402. 'THUMBSTICK_X',
  65403. 'THUMBSTICK_Y',
  65404. 'TOUCHPAD_TOUCH_X',
  65405. 'TOUCHPAD_TOUCH_Y'
  65406. ],
  65407. pointingPoseMeshName: 'POINTING_POSE'
  65408. };
  65409. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  65410. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  65411. _this.trackpad = { x: 0, y: 0 };
  65412. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  65413. _this._loadedMeshInfo = null;
  65414. return _this;
  65415. }
  65416. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  65417. get: function () {
  65418. return this.onTriggerStateChangedObservable;
  65419. },
  65420. enumerable: true,
  65421. configurable: true
  65422. });
  65423. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  65424. get: function () {
  65425. return this.onSecondaryButtonStateChangedObservable;
  65426. },
  65427. enumerable: true,
  65428. configurable: true
  65429. });
  65430. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  65431. get: function () {
  65432. return this.onMainButtonStateChangedObservable;
  65433. },
  65434. enumerable: true,
  65435. configurable: true
  65436. });
  65437. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  65438. get: function () {
  65439. return this.onPadStateChangedObservable;
  65440. },
  65441. enumerable: true,
  65442. configurable: true
  65443. });
  65444. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  65445. get: function () {
  65446. return this.onTrackpadChangedObservable;
  65447. },
  65448. enumerable: true,
  65449. configurable: true
  65450. });
  65451. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  65452. get: function () {
  65453. return this.onTrackpadValuesChangedObservable;
  65454. },
  65455. enumerable: true,
  65456. configurable: true
  65457. });
  65458. /**
  65459. * Called once per frame by the engine.
  65460. */
  65461. WindowsMotionController.prototype.update = function () {
  65462. _super.prototype.update.call(this);
  65463. // Only need to animate axes if there is a loaded mesh
  65464. if (this._loadedMeshInfo) {
  65465. if (this.browserGamepad.axes) {
  65466. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  65467. this.trackpad.x = this.browserGamepad["axes"][2];
  65468. this.trackpad.y = this.browserGamepad["axes"][3];
  65469. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  65470. }
  65471. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  65472. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  65473. }
  65474. }
  65475. }
  65476. };
  65477. /**
  65478. * Called once for each button that changed state since the last frame
  65479. * @param buttonIdx Which button index changed
  65480. * @param state New state of the button
  65481. * @param changes Which properties on the state changed since last frame
  65482. */
  65483. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  65484. var buttonName = this._mapping.buttons[buttonIdx];
  65485. if (!buttonName) {
  65486. return;
  65487. }
  65488. // Only emit events for buttons that we know how to map from index to name
  65489. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  65490. if (observable) {
  65491. observable.notifyObservers(state);
  65492. }
  65493. this.lerpButtonTransform(buttonName, state.value);
  65494. };
  65495. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  65496. // If there is no loaded mesh, there is nothing to transform.
  65497. if (!this._loadedMeshInfo) {
  65498. return;
  65499. }
  65500. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  65501. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  65502. return;
  65503. }
  65504. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  65505. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  65506. };
  65507. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  65508. if (!this._loadedMeshInfo) {
  65509. return;
  65510. }
  65511. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  65512. if (!meshInfo) {
  65513. return;
  65514. }
  65515. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  65516. return;
  65517. }
  65518. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  65519. var lerpValue = axisValue * 0.5 + 0.5;
  65520. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  65521. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  65522. };
  65523. /**
  65524. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  65525. * @param scene scene in which to add meshes
  65526. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  65527. */
  65528. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  65529. var _this = this;
  65530. if (forceDefault === void 0) { forceDefault = false; }
  65531. var path;
  65532. var filename;
  65533. // Checking if GLB loader is present
  65534. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  65535. // Determine the device specific folder based on the ID suffix
  65536. var device = 'default';
  65537. if (this.id && !forceDefault) {
  65538. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  65539. device = ((match && match[0]) || device);
  65540. }
  65541. // Hand
  65542. if (this.hand === 'left') {
  65543. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  65544. }
  65545. else {
  65546. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  65547. }
  65548. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  65549. }
  65550. else {
  65551. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  65552. path = BABYLON.GenericController.MODEL_BASE_URL;
  65553. filename = BABYLON.GenericController.MODEL_FILENAME;
  65554. }
  65555. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  65556. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  65557. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  65558. if (!_this._loadedMeshInfo) {
  65559. return;
  65560. }
  65561. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  65562. _this.attachToMesh(_this._defaultModel);
  65563. if (meshLoaded) {
  65564. meshLoaded(_this._defaultModel);
  65565. }
  65566. }, null, function (scene, message) {
  65567. BABYLON.Tools.Log(message);
  65568. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  65569. if (!forceDefault) {
  65570. _this.initControllerMesh(scene, meshLoaded, true);
  65571. }
  65572. });
  65573. };
  65574. /**
  65575. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  65576. * can be transformed by button presses and axes values, based on this._mapping.
  65577. *
  65578. * @param scene scene in which the meshes exist
  65579. * @param meshes list of meshes that make up the controller model to process
  65580. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  65581. */
  65582. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  65583. var loadedMeshInfo = null;
  65584. // Create a new mesh to contain the glTF hierarchy
  65585. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  65586. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  65587. var childMesh = null;
  65588. for (var i = 0; i < meshes.length; i++) {
  65589. var mesh = meshes[i];
  65590. if (!mesh.parent) {
  65591. // Exclude controller meshes from picking results
  65592. mesh.isPickable = false;
  65593. // Handle root node, attach to the new parentMesh
  65594. childMesh = mesh;
  65595. break;
  65596. }
  65597. }
  65598. if (childMesh) {
  65599. childMesh.setParent(parentMesh);
  65600. // Create our mesh info. Note that this method will always return non-null.
  65601. loadedMeshInfo = this.createMeshInfo(parentMesh);
  65602. }
  65603. else {
  65604. BABYLON.Tools.Warn('Could not find root node in model file.');
  65605. }
  65606. return loadedMeshInfo;
  65607. };
  65608. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  65609. var loadedMeshInfo = new LoadedMeshInfo();
  65610. var i;
  65611. loadedMeshInfo.rootNode = rootNode;
  65612. // Reset the caches
  65613. loadedMeshInfo.buttonMeshes = {};
  65614. loadedMeshInfo.axisMeshes = {};
  65615. // Button Meshes
  65616. for (i = 0; i < this._mapping.buttons.length; i++) {
  65617. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  65618. if (!buttonMeshName) {
  65619. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  65620. continue;
  65621. }
  65622. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  65623. if (!buttonMesh) {
  65624. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  65625. continue;
  65626. }
  65627. var buttonMeshInfo = {
  65628. index: i,
  65629. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  65630. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  65631. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  65632. };
  65633. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  65634. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  65635. }
  65636. else {
  65637. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  65638. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  65639. '(VALUE: ' + !!buttonMeshInfo.value +
  65640. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  65641. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  65642. ')');
  65643. }
  65644. }
  65645. // Axis Meshes
  65646. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  65647. var axisMeshName = this._mapping.axisMeshNames[i];
  65648. if (!axisMeshName) {
  65649. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  65650. continue;
  65651. }
  65652. var axisMesh = getChildByName(rootNode, axisMeshName);
  65653. if (!axisMesh) {
  65654. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  65655. continue;
  65656. }
  65657. var axisMeshInfo = {
  65658. index: i,
  65659. value: getImmediateChildByName(axisMesh, 'VALUE'),
  65660. min: getImmediateChildByName(axisMesh, 'MIN'),
  65661. max: getImmediateChildByName(axisMesh, 'MAX')
  65662. };
  65663. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  65664. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  65665. }
  65666. else {
  65667. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  65668. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  65669. '(VALUE: ' + !!axisMeshInfo.value +
  65670. ', MIN: ' + !!axisMeshInfo.min +
  65671. ', MAX:' + !!axisMeshInfo.max +
  65672. ')');
  65673. }
  65674. }
  65675. // Pointing Ray
  65676. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  65677. if (!loadedMeshInfo.pointingPoseNode) {
  65678. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  65679. }
  65680. return loadedMeshInfo;
  65681. // Look through all children recursively. This will return null if no mesh exists with the given name.
  65682. function getChildByName(node, name) {
  65683. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  65684. }
  65685. // Look through only immediate children. This will return null if no mesh exists with the given name.
  65686. function getImmediateChildByName(node, name) {
  65687. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  65688. }
  65689. };
  65690. WindowsMotionController.prototype.getForwardRay = function (length) {
  65691. if (length === void 0) { length = 100; }
  65692. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  65693. return _super.prototype.getForwardRay.call(this, length);
  65694. }
  65695. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  65696. var origin = m.getTranslation();
  65697. var forward = new BABYLON.Vector3(0, 0, -1);
  65698. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  65699. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  65700. return new BABYLON.Ray(origin, direction, length);
  65701. };
  65702. WindowsMotionController.prototype.dispose = function () {
  65703. _super.prototype.dispose.call(this);
  65704. this.onTrackpadChangedObservable.clear();
  65705. };
  65706. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  65707. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  65708. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  65709. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  65710. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  65711. return WindowsMotionController;
  65712. }(BABYLON.WebVRController));
  65713. BABYLON.WindowsMotionController = WindowsMotionController;
  65714. })(BABYLON || (BABYLON = {}));
  65715. //# sourceMappingURL=babylon.windowsMotionController.js.map
  65716. var BABYLON;
  65717. (function (BABYLON) {
  65718. var GearVRController = /** @class */ (function (_super) {
  65719. __extends(GearVRController, _super);
  65720. function GearVRController(vrGamepad) {
  65721. var _this = _super.call(this, vrGamepad) || this;
  65722. _this._buttonIndexToObservableNameMap = [
  65723. 'onTrackpadChangedObservable',
  65724. 'onTriggerStateChangedObservable' // Trigger
  65725. ];
  65726. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  65727. return _this;
  65728. }
  65729. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65730. var _this = this;
  65731. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  65732. _this._defaultModel = newMeshes[1];
  65733. _this.attachToMesh(_this._defaultModel);
  65734. if (meshLoaded) {
  65735. meshLoaded(_this._defaultModel);
  65736. }
  65737. });
  65738. };
  65739. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  65740. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  65741. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  65742. // Only emit events for buttons that we know how to map from index to observable
  65743. var observable = this[observableName];
  65744. if (observable) {
  65745. observable.notifyObservers(state);
  65746. }
  65747. }
  65748. };
  65749. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65750. GearVRController.MODEL_FILENAME = 'generic.babylon';
  65751. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  65752. return GearVRController;
  65753. }(BABYLON.WebVRController));
  65754. BABYLON.GearVRController = GearVRController;
  65755. })(BABYLON || (BABYLON = {}));
  65756. //# sourceMappingURL=babylon.gearVRController.js.map
  65757. var BABYLON;
  65758. (function (BABYLON) {
  65759. var FollowCamera = /** @class */ (function (_super) {
  65760. __extends(FollowCamera, _super);
  65761. function FollowCamera(name, position, scene, lockedTarget) {
  65762. if (lockedTarget === void 0) { lockedTarget = null; }
  65763. var _this = _super.call(this, name, position, scene) || this;
  65764. _this.radius = 12;
  65765. _this.rotationOffset = 0;
  65766. _this.heightOffset = 4;
  65767. _this.cameraAcceleration = 0.05;
  65768. _this.maxCameraSpeed = 20;
  65769. _this.lockedTarget = lockedTarget;
  65770. return _this;
  65771. }
  65772. FollowCamera.prototype.getRadians = function (degrees) {
  65773. return degrees * Math.PI / 180;
  65774. };
  65775. FollowCamera.prototype.follow = function (cameraTarget) {
  65776. if (!cameraTarget)
  65777. return;
  65778. var yRotation;
  65779. if (cameraTarget.rotationQuaternion) {
  65780. var rotMatrix = new BABYLON.Matrix();
  65781. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  65782. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  65783. }
  65784. else {
  65785. yRotation = cameraTarget.rotation.y;
  65786. }
  65787. var radians = this.getRadians(this.rotationOffset) + yRotation;
  65788. var targetPosition = cameraTarget.getAbsolutePosition();
  65789. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  65790. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  65791. var dx = targetX - this.position.x;
  65792. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  65793. var dz = (targetZ) - this.position.z;
  65794. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  65795. var vy = dy * this.cameraAcceleration;
  65796. var vz = dz * this.cameraAcceleration * 2;
  65797. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  65798. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65799. }
  65800. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  65801. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65802. }
  65803. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  65804. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65805. }
  65806. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  65807. this.setTarget(targetPosition);
  65808. };
  65809. FollowCamera.prototype._checkInputs = function () {
  65810. _super.prototype._checkInputs.call(this);
  65811. if (this.lockedTarget) {
  65812. this.follow(this.lockedTarget);
  65813. }
  65814. };
  65815. FollowCamera.prototype.getClassName = function () {
  65816. return "FollowCamera";
  65817. };
  65818. __decorate([
  65819. BABYLON.serialize()
  65820. ], FollowCamera.prototype, "radius", void 0);
  65821. __decorate([
  65822. BABYLON.serialize()
  65823. ], FollowCamera.prototype, "rotationOffset", void 0);
  65824. __decorate([
  65825. BABYLON.serialize()
  65826. ], FollowCamera.prototype, "heightOffset", void 0);
  65827. __decorate([
  65828. BABYLON.serialize()
  65829. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  65830. __decorate([
  65831. BABYLON.serialize()
  65832. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  65833. __decorate([
  65834. BABYLON.serializeAsMeshReference("lockedTargetId")
  65835. ], FollowCamera.prototype, "lockedTarget", void 0);
  65836. return FollowCamera;
  65837. }(BABYLON.TargetCamera));
  65838. BABYLON.FollowCamera = FollowCamera;
  65839. var ArcFollowCamera = /** @class */ (function (_super) {
  65840. __extends(ArcFollowCamera, _super);
  65841. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  65842. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  65843. _this.alpha = alpha;
  65844. _this.beta = beta;
  65845. _this.radius = radius;
  65846. _this.target = target;
  65847. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  65848. _this.follow();
  65849. return _this;
  65850. }
  65851. ArcFollowCamera.prototype.follow = function () {
  65852. if (!this.target) {
  65853. return;
  65854. }
  65855. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  65856. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  65857. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  65858. var targetPosition = this.target.getAbsolutePosition();
  65859. this.position = targetPosition.add(this._cartesianCoordinates);
  65860. this.setTarget(targetPosition);
  65861. };
  65862. ArcFollowCamera.prototype._checkInputs = function () {
  65863. _super.prototype._checkInputs.call(this);
  65864. this.follow();
  65865. };
  65866. ArcFollowCamera.prototype.getClassName = function () {
  65867. return "ArcFollowCamera";
  65868. };
  65869. return ArcFollowCamera;
  65870. }(BABYLON.TargetCamera));
  65871. BABYLON.ArcFollowCamera = ArcFollowCamera;
  65872. })(BABYLON || (BABYLON = {}));
  65873. //# sourceMappingURL=babylon.followCamera.js.map
  65874. var BABYLON;
  65875. (function (BABYLON) {
  65876. // We're mainly based on the logic defined into the FreeCamera code
  65877. var UniversalCamera = /** @class */ (function (_super) {
  65878. __extends(UniversalCamera, _super);
  65879. //-- end properties for backward compatibility for inputs
  65880. function UniversalCamera(name, position, scene) {
  65881. var _this = _super.call(this, name, position, scene) || this;
  65882. _this.inputs.addGamepad();
  65883. return _this;
  65884. }
  65885. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  65886. //-- Begin properties for backward compatibility for inputs
  65887. get: function () {
  65888. var gamepad = this.inputs.attached["gamepad"];
  65889. if (gamepad)
  65890. return gamepad.gamepadAngularSensibility;
  65891. return 0;
  65892. },
  65893. set: function (value) {
  65894. var gamepad = this.inputs.attached["gamepad"];
  65895. if (gamepad)
  65896. gamepad.gamepadAngularSensibility = value;
  65897. },
  65898. enumerable: true,
  65899. configurable: true
  65900. });
  65901. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  65902. get: function () {
  65903. var gamepad = this.inputs.attached["gamepad"];
  65904. if (gamepad)
  65905. return gamepad.gamepadMoveSensibility;
  65906. return 0;
  65907. },
  65908. set: function (value) {
  65909. var gamepad = this.inputs.attached["gamepad"];
  65910. if (gamepad)
  65911. gamepad.gamepadMoveSensibility = value;
  65912. },
  65913. enumerable: true,
  65914. configurable: true
  65915. });
  65916. UniversalCamera.prototype.getClassName = function () {
  65917. return "UniversalCamera";
  65918. };
  65919. return UniversalCamera;
  65920. }(BABYLON.TouchCamera));
  65921. BABYLON.UniversalCamera = UniversalCamera;
  65922. })(BABYLON || (BABYLON = {}));
  65923. //# sourceMappingURL=babylon.universalCamera.js.map
  65924. var BABYLON;
  65925. (function (BABYLON) {
  65926. // We're mainly based on the logic defined into the FreeCamera code
  65927. var GamepadCamera = /** @class */ (function (_super) {
  65928. __extends(GamepadCamera, _super);
  65929. //-- end properties for backward compatibility for inputs
  65930. function GamepadCamera(name, position, scene) {
  65931. return _super.call(this, name, position, scene) || this;
  65932. }
  65933. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  65934. //-- Begin properties for backward compatibility for inputs
  65935. get: function () {
  65936. var gamepad = this.inputs.attached["gamepad"];
  65937. if (gamepad)
  65938. return gamepad.gamepadAngularSensibility;
  65939. return 0;
  65940. },
  65941. set: function (value) {
  65942. var gamepad = this.inputs.attached["gamepad"];
  65943. if (gamepad)
  65944. gamepad.gamepadAngularSensibility = value;
  65945. },
  65946. enumerable: true,
  65947. configurable: true
  65948. });
  65949. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  65950. get: function () {
  65951. var gamepad = this.inputs.attached["gamepad"];
  65952. if (gamepad)
  65953. return gamepad.gamepadMoveSensibility;
  65954. return 0;
  65955. },
  65956. set: function (value) {
  65957. var gamepad = this.inputs.attached["gamepad"];
  65958. if (gamepad)
  65959. gamepad.gamepadMoveSensibility = value;
  65960. },
  65961. enumerable: true,
  65962. configurable: true
  65963. });
  65964. GamepadCamera.prototype.getClassName = function () {
  65965. return "GamepadCamera";
  65966. };
  65967. return GamepadCamera;
  65968. }(BABYLON.UniversalCamera));
  65969. BABYLON.GamepadCamera = GamepadCamera;
  65970. })(BABYLON || (BABYLON = {}));
  65971. //# sourceMappingURL=babylon.gamepadCamera.js.map
  65972. var BABYLON;
  65973. (function (BABYLON) {
  65974. var PostProcessRenderPipelineManager = /** @class */ (function () {
  65975. function PostProcessRenderPipelineManager() {
  65976. this._renderPipelines = {};
  65977. }
  65978. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  65979. this._renderPipelines[renderPipeline._name] = renderPipeline;
  65980. };
  65981. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  65982. if (unique === void 0) { unique = false; }
  65983. var renderPipeline = this._renderPipelines[renderPipelineName];
  65984. if (!renderPipeline) {
  65985. return;
  65986. }
  65987. renderPipeline._attachCameras(cameras, unique);
  65988. };
  65989. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  65990. var renderPipeline = this._renderPipelines[renderPipelineName];
  65991. if (!renderPipeline) {
  65992. return;
  65993. }
  65994. renderPipeline._detachCameras(cameras);
  65995. };
  65996. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  65997. var renderPipeline = this._renderPipelines[renderPipelineName];
  65998. if (!renderPipeline) {
  65999. return;
  66000. }
  66001. renderPipeline._enableEffect(renderEffectName, cameras);
  66002. };
  66003. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  66004. var renderPipeline = this._renderPipelines[renderPipelineName];
  66005. if (!renderPipeline) {
  66006. return;
  66007. }
  66008. renderPipeline._disableEffect(renderEffectName, cameras);
  66009. };
  66010. PostProcessRenderPipelineManager.prototype.update = function () {
  66011. for (var renderPipelineName in this._renderPipelines) {
  66012. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66013. var pipeline = this._renderPipelines[renderPipelineName];
  66014. if (!pipeline.isSupported) {
  66015. pipeline.dispose();
  66016. delete this._renderPipelines[renderPipelineName];
  66017. }
  66018. else {
  66019. pipeline._update();
  66020. }
  66021. }
  66022. }
  66023. };
  66024. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  66025. for (var renderPipelineName in this._renderPipelines) {
  66026. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66027. var pipeline = this._renderPipelines[renderPipelineName];
  66028. pipeline._rebuild();
  66029. }
  66030. }
  66031. };
  66032. PostProcessRenderPipelineManager.prototype.dispose = function () {
  66033. for (var renderPipelineName in this._renderPipelines) {
  66034. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66035. var pipeline = this._renderPipelines[renderPipelineName];
  66036. pipeline.dispose();
  66037. }
  66038. }
  66039. };
  66040. return PostProcessRenderPipelineManager;
  66041. }());
  66042. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  66043. })(BABYLON || (BABYLON = {}));
  66044. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  66045. var BABYLON;
  66046. (function (BABYLON) {
  66047. /**
  66048. * This represents a set of one or more post processes in Babylon.
  66049. * A post process can be used to apply a shader to a texture after it is rendered.
  66050. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  66051. */
  66052. var PostProcessRenderEffect = /** @class */ (function () {
  66053. /**
  66054. * Instantiates a post process render effect.
  66055. * A post process can be used to apply a shader to a texture after it is rendered.
  66056. * @param engine The engine the effect is tied to
  66057. * @param name The name of the effect
  66058. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  66059. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  66060. */
  66061. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  66062. this._name = name;
  66063. this._singleInstance = singleInstance || true;
  66064. this._getPostProcesses = getPostProcesses;
  66065. this._cameras = {};
  66066. this._indicesForCamera = {};
  66067. this._postProcesses = {};
  66068. }
  66069. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  66070. /**
  66071. * Checks if all the post processes in the effect are supported.
  66072. */
  66073. get: function () {
  66074. for (var index in this._postProcesses) {
  66075. for (var ppIndex in this._postProcesses[index]) {
  66076. if (!this._postProcesses[index][ppIndex].isSupported) {
  66077. return false;
  66078. }
  66079. }
  66080. }
  66081. return true;
  66082. },
  66083. enumerable: true,
  66084. configurable: true
  66085. });
  66086. /**
  66087. * Updates the current state of the effect
  66088. */
  66089. PostProcessRenderEffect.prototype._update = function () {
  66090. };
  66091. /**
  66092. * Attaches the effect on cameras
  66093. * @param cameras The camera to attach to.
  66094. */
  66095. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  66096. var _this = this;
  66097. var cameraKey;
  66098. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66099. if (!cams) {
  66100. return;
  66101. }
  66102. for (var i = 0; i < cams.length; i++) {
  66103. var camera = cams[i];
  66104. var cameraName = camera.name;
  66105. if (this._singleInstance) {
  66106. cameraKey = 0;
  66107. }
  66108. else {
  66109. cameraKey = cameraName;
  66110. }
  66111. if (!this._postProcesses[cameraKey]) {
  66112. var postProcess = this._getPostProcesses();
  66113. if (postProcess) {
  66114. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  66115. }
  66116. }
  66117. if (!this._indicesForCamera[cameraName]) {
  66118. this._indicesForCamera[cameraName] = [];
  66119. }
  66120. this._postProcesses[cameraKey].forEach(function (postProcess) {
  66121. var index = camera.attachPostProcess(postProcess);
  66122. _this._indicesForCamera[cameraName].push(index);
  66123. });
  66124. if (!this._cameras[cameraName]) {
  66125. this._cameras[cameraName] = camera;
  66126. }
  66127. }
  66128. };
  66129. /**
  66130. * Detatches the effect on cameras
  66131. * @param cameras The camera to detatch from.
  66132. */
  66133. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  66134. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66135. if (!cams) {
  66136. return;
  66137. }
  66138. for (var i = 0; i < cams.length; i++) {
  66139. var camera = cams[i];
  66140. var cameraName = camera.name;
  66141. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66142. camera.detachPostProcess(postProcess);
  66143. });
  66144. if (this._cameras[cameraName]) {
  66145. //this._indicesForCamera.splice(index, 1);
  66146. this._cameras[cameraName] = null;
  66147. }
  66148. }
  66149. };
  66150. /**
  66151. * Enables the effect on given cameras
  66152. * @param cameras The camera to enable.
  66153. */
  66154. PostProcessRenderEffect.prototype._enable = function (cameras) {
  66155. var _this = this;
  66156. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66157. if (!cams) {
  66158. return;
  66159. }
  66160. for (var i = 0; i < cams.length; i++) {
  66161. var camera = cams[i];
  66162. var cameraName = camera.name;
  66163. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  66164. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  66165. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66166. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  66167. });
  66168. }
  66169. }
  66170. }
  66171. };
  66172. /**
  66173. * Disables the effect on the given cameras
  66174. * @param cameras The camera to disable.
  66175. */
  66176. PostProcessRenderEffect.prototype._disable = function (cameras) {
  66177. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66178. if (!cams) {
  66179. return;
  66180. }
  66181. for (var i = 0; i < cams.length; i++) {
  66182. var camera = cams[i];
  66183. var cameraName = camera.name;
  66184. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66185. camera.detachPostProcess(postProcess);
  66186. });
  66187. }
  66188. };
  66189. /**
  66190. * Gets a list of the post processes contained in the effect.
  66191. * @param camera The camera to get the post processes on.
  66192. * @returns The list of the post processes in the effect.
  66193. */
  66194. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  66195. if (this._singleInstance) {
  66196. return this._postProcesses[0];
  66197. }
  66198. else {
  66199. if (!camera) {
  66200. return null;
  66201. }
  66202. return this._postProcesses[camera.name];
  66203. }
  66204. };
  66205. return PostProcessRenderEffect;
  66206. }());
  66207. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  66208. })(BABYLON || (BABYLON = {}));
  66209. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  66210. var BABYLON;
  66211. (function (BABYLON) {
  66212. var PostProcessRenderPipeline = /** @class */ (function () {
  66213. function PostProcessRenderPipeline(engine, name) {
  66214. this.engine = engine;
  66215. this._name = name;
  66216. this._renderEffects = {};
  66217. this._renderEffectsForIsolatedPass = new Array();
  66218. this._cameras = [];
  66219. }
  66220. PostProcessRenderPipeline.prototype.getClassName = function () {
  66221. return "PostProcessRenderPipeline";
  66222. };
  66223. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  66224. get: function () {
  66225. for (var renderEffectName in this._renderEffects) {
  66226. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66227. if (!this._renderEffects[renderEffectName].isSupported) {
  66228. return false;
  66229. }
  66230. }
  66231. }
  66232. return true;
  66233. },
  66234. enumerable: true,
  66235. configurable: true
  66236. });
  66237. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  66238. this._renderEffects[renderEffect._name] = renderEffect;
  66239. };
  66240. // private
  66241. PostProcessRenderPipeline.prototype._rebuild = function () {
  66242. };
  66243. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  66244. var renderEffects = this._renderEffects[renderEffectName];
  66245. if (!renderEffects) {
  66246. return;
  66247. }
  66248. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  66249. };
  66250. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  66251. var renderEffects = this._renderEffects[renderEffectName];
  66252. if (!renderEffects) {
  66253. return;
  66254. }
  66255. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  66256. };
  66257. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  66258. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66259. if (!cams) {
  66260. return;
  66261. }
  66262. var indicesToDelete = [];
  66263. var i;
  66264. for (i = 0; i < cams.length; i++) {
  66265. var camera = cams[i];
  66266. var cameraName = camera.name;
  66267. if (this._cameras.indexOf(camera) === -1) {
  66268. this._cameras[cameraName] = camera;
  66269. }
  66270. else if (unique) {
  66271. indicesToDelete.push(i);
  66272. }
  66273. }
  66274. for (i = 0; i < indicesToDelete.length; i++) {
  66275. cameras.splice(indicesToDelete[i], 1);
  66276. }
  66277. for (var renderEffectName in this._renderEffects) {
  66278. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66279. this._renderEffects[renderEffectName]._attachCameras(cams);
  66280. }
  66281. }
  66282. };
  66283. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  66284. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66285. if (!cams) {
  66286. return;
  66287. }
  66288. for (var renderEffectName in this._renderEffects) {
  66289. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66290. this._renderEffects[renderEffectName]._detachCameras(cams);
  66291. }
  66292. }
  66293. for (var i = 0; i < cams.length; i++) {
  66294. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  66295. }
  66296. };
  66297. PostProcessRenderPipeline.prototype._update = function () {
  66298. for (var renderEffectName in this._renderEffects) {
  66299. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66300. this._renderEffects[renderEffectName]._update();
  66301. }
  66302. }
  66303. for (var i = 0; i < this._cameras.length; i++) {
  66304. var cameraName = this._cameras[i].name;
  66305. if (this._renderEffectsForIsolatedPass[cameraName]) {
  66306. this._renderEffectsForIsolatedPass[cameraName]._update();
  66307. }
  66308. }
  66309. };
  66310. PostProcessRenderPipeline.prototype._reset = function () {
  66311. this._renderEffects = {};
  66312. this._renderEffectsForIsolatedPass = new Array();
  66313. };
  66314. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function () {
  66315. // 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)
  66316. var effectKeys = Object.keys(this._renderEffects);
  66317. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  66318. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  66319. if (postProcesses) {
  66320. postProcesses[0].samples = 4;
  66321. return true;
  66322. }
  66323. }
  66324. return false;
  66325. };
  66326. PostProcessRenderPipeline.prototype.dispose = function () {
  66327. // Must be implemented by children
  66328. };
  66329. __decorate([
  66330. BABYLON.serialize()
  66331. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  66332. return PostProcessRenderPipeline;
  66333. }());
  66334. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  66335. })(BABYLON || (BABYLON = {}));
  66336. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  66337. var BABYLON;
  66338. (function (BABYLON) {
  66339. /**
  66340. * This represents a depth renderer in Babylon.
  66341. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  66342. */
  66343. var DepthRenderer = /** @class */ (function () {
  66344. /**
  66345. * Instantiates a depth renderer
  66346. * @param scene The scene the renderer belongs to
  66347. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  66348. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  66349. */
  66350. function DepthRenderer(scene, type, camera) {
  66351. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  66352. if (camera === void 0) { camera = null; }
  66353. var _this = this;
  66354. this._scene = scene;
  66355. this._camera = camera;
  66356. var engine = scene.getEngine();
  66357. // Render target
  66358. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  66359. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66360. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66361. this._depthMap.refreshRate = 1;
  66362. this._depthMap.renderParticles = false;
  66363. this._depthMap.renderList = null;
  66364. // Camera to get depth map from to support multiple concurrent cameras
  66365. this._depthMap.activeCamera = this._camera;
  66366. this._depthMap.ignoreCameraViewport = true;
  66367. this._depthMap.useCameraPostProcesses = false;
  66368. // set default depth value to 1.0 (far away)
  66369. this._depthMap.onClearObservable.add(function (engine) {
  66370. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  66371. });
  66372. // Custom render function
  66373. var renderSubMesh = function (subMesh) {
  66374. var mesh = subMesh.getRenderingMesh();
  66375. var scene = _this._scene;
  66376. var engine = scene.getEngine();
  66377. var material = subMesh.getMaterial();
  66378. if (!material) {
  66379. return;
  66380. }
  66381. // Culling and reverse (right handed system)
  66382. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  66383. // Managing instances
  66384. var batch = mesh._getInstancesRenderList(subMesh._id);
  66385. if (batch.mustReturn) {
  66386. return;
  66387. }
  66388. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  66389. var camera = _this._camera || scene.activeCamera;
  66390. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  66391. engine.enableEffect(_this._effect);
  66392. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  66393. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  66394. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  66395. // Alpha test
  66396. if (material && material.needAlphaTesting()) {
  66397. var alphaTexture = material.getAlphaTestTexture();
  66398. if (alphaTexture) {
  66399. _this._effect.setTexture("diffuseSampler", alphaTexture);
  66400. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  66401. }
  66402. }
  66403. // Bones
  66404. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  66405. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  66406. }
  66407. // Draw
  66408. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66409. }
  66410. };
  66411. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66412. var index;
  66413. if (depthOnlySubMeshes.length) {
  66414. engine.setColorWrite(false);
  66415. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66416. renderSubMesh(depthOnlySubMeshes.data[index]);
  66417. }
  66418. engine.setColorWrite(true);
  66419. }
  66420. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66421. renderSubMesh(opaqueSubMeshes.data[index]);
  66422. }
  66423. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66424. renderSubMesh(alphaTestSubMeshes.data[index]);
  66425. }
  66426. };
  66427. }
  66428. /**
  66429. * Creates the depth rendering effect and checks if the effect is ready.
  66430. * @param subMesh The submesh to be used to render the depth map of
  66431. * @param useInstances If multiple world instances should be used
  66432. * @returns if the depth renderer is ready to render the depth map
  66433. */
  66434. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  66435. var material = subMesh.getMaterial();
  66436. if (material.disableDepthWrite) {
  66437. return false;
  66438. }
  66439. var defines = [];
  66440. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66441. var mesh = subMesh.getMesh();
  66442. // Alpha test
  66443. if (material && material.needAlphaTesting()) {
  66444. defines.push("#define ALPHATEST");
  66445. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66446. attribs.push(BABYLON.VertexBuffer.UVKind);
  66447. defines.push("#define UV1");
  66448. }
  66449. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66450. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66451. defines.push("#define UV2");
  66452. }
  66453. }
  66454. // Bones
  66455. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66456. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66457. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66458. if (mesh.numBoneInfluencers > 4) {
  66459. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66460. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66461. }
  66462. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66463. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  66464. }
  66465. else {
  66466. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66467. }
  66468. // Instances
  66469. if (useInstances) {
  66470. defines.push("#define INSTANCES");
  66471. attribs.push("world0");
  66472. attribs.push("world1");
  66473. attribs.push("world2");
  66474. attribs.push("world3");
  66475. }
  66476. // Get correct effect
  66477. var join = defines.join("\n");
  66478. if (this._cachedDefines !== join) {
  66479. this._cachedDefines = join;
  66480. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  66481. }
  66482. return this._effect.isReady();
  66483. };
  66484. /**
  66485. * Gets the texture which the depth map will be written to.
  66486. * @returns The depth map texture
  66487. */
  66488. DepthRenderer.prototype.getDepthMap = function () {
  66489. return this._depthMap;
  66490. };
  66491. /**
  66492. * Disposes of the depth renderer.
  66493. */
  66494. DepthRenderer.prototype.dispose = function () {
  66495. this._depthMap.dispose();
  66496. };
  66497. return DepthRenderer;
  66498. }());
  66499. BABYLON.DepthRenderer = DepthRenderer;
  66500. })(BABYLON || (BABYLON = {}));
  66501. //# sourceMappingURL=babylon.depthRenderer.js.map
  66502. var BABYLON;
  66503. (function (BABYLON) {
  66504. var SSAORenderingPipeline = /** @class */ (function (_super) {
  66505. __extends(SSAORenderingPipeline, _super);
  66506. /**
  66507. * @constructor
  66508. * @param {string} name - The rendering pipeline name
  66509. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66510. * @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 }
  66511. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66512. */
  66513. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  66514. var _this = _super.call(this, scene.getEngine(), name) || this;
  66515. // Members
  66516. /**
  66517. * The PassPostProcess id in the pipeline that contains the original scene color
  66518. * @type {string}
  66519. */
  66520. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  66521. /**
  66522. * The SSAO PostProcess id in the pipeline
  66523. * @type {string}
  66524. */
  66525. _this.SSAORenderEffect = "SSAORenderEffect";
  66526. /**
  66527. * The horizontal blur PostProcess id in the pipeline
  66528. * @type {string}
  66529. */
  66530. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  66531. /**
  66532. * The vertical blur PostProcess id in the pipeline
  66533. * @type {string}
  66534. */
  66535. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  66536. /**
  66537. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  66538. * @type {string}
  66539. */
  66540. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  66541. /**
  66542. * The output strength of the SSAO post-process. Default value is 1.0.
  66543. * @type {number}
  66544. */
  66545. _this.totalStrength = 1.0;
  66546. /**
  66547. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  66548. * @type {number}
  66549. */
  66550. _this.radius = 0.0001;
  66551. /**
  66552. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  66553. * Must not be equal to fallOff and superior to fallOff.
  66554. * Default value is 0.975
  66555. * @type {number}
  66556. */
  66557. _this.area = 0.0075;
  66558. /**
  66559. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  66560. * Must not be equal to area and inferior to area.
  66561. * Default value is 0.0
  66562. * @type {number}
  66563. */
  66564. _this.fallOff = 0.000001;
  66565. /**
  66566. * The base color of the SSAO post-process
  66567. * The final result is "base + ssao" between [0, 1]
  66568. * @type {number}
  66569. */
  66570. _this.base = 0.5;
  66571. _this._firstUpdate = true;
  66572. _this._scene = scene;
  66573. // Set up assets
  66574. _this._createRandomTexture();
  66575. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  66576. var ssaoRatio = ratio.ssaoRatio || ratio;
  66577. var combineRatio = ratio.combineRatio || ratio;
  66578. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  66579. _this._createSSAOPostProcess(ssaoRatio);
  66580. _this._createBlurPostProcess(ssaoRatio);
  66581. _this._createSSAOCombinePostProcess(combineRatio);
  66582. // Set up pipeline
  66583. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  66584. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  66585. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  66586. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  66587. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  66588. // Finish
  66589. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66590. if (cameras)
  66591. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66592. return _this;
  66593. }
  66594. // Public Methods
  66595. /**
  66596. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  66597. */
  66598. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  66599. if (disableDepthRender === void 0) { disableDepthRender = false; }
  66600. for (var i = 0; i < this._scene.cameras.length; i++) {
  66601. var camera = this._scene.cameras[i];
  66602. this._originalColorPostProcess.dispose(camera);
  66603. this._ssaoPostProcess.dispose(camera);
  66604. this._blurHPostProcess.dispose(camera);
  66605. this._blurVPostProcess.dispose(camera);
  66606. this._ssaoCombinePostProcess.dispose(camera);
  66607. }
  66608. this._randomTexture.dispose();
  66609. if (disableDepthRender)
  66610. this._scene.disableDepthRenderer();
  66611. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66612. _super.prototype.dispose.call(this);
  66613. };
  66614. // Private Methods
  66615. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  66616. var _this = this;
  66617. var size = 16;
  66618. 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);
  66619. 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);
  66620. this._blurHPostProcess.onActivateObservable.add(function () {
  66621. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  66622. _this._blurHPostProcess.kernel = size * dw;
  66623. });
  66624. this._blurVPostProcess.onActivateObservable.add(function () {
  66625. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  66626. _this._blurVPostProcess.kernel = size * dw;
  66627. });
  66628. };
  66629. SSAORenderingPipeline.prototype._rebuild = function () {
  66630. this._firstUpdate = true;
  66631. _super.prototype._rebuild.call(this);
  66632. };
  66633. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  66634. var _this = this;
  66635. var numSamples = 16;
  66636. var sampleSphere = [
  66637. 0.5381, 0.1856, -0.4319,
  66638. 0.1379, 0.2486, 0.4430,
  66639. 0.3371, 0.5679, -0.0057,
  66640. -0.6999, -0.0451, -0.0019,
  66641. 0.0689, -0.1598, -0.8547,
  66642. 0.0560, 0.0069, -0.1843,
  66643. -0.0146, 0.1402, 0.0762,
  66644. 0.0100, -0.1924, -0.0344,
  66645. -0.3577, -0.5301, -0.4358,
  66646. -0.3169, 0.1063, 0.0158,
  66647. 0.0103, -0.5869, 0.0046,
  66648. -0.0897, -0.4940, 0.3287,
  66649. 0.7119, -0.0154, -0.0918,
  66650. -0.0533, 0.0596, -0.5411,
  66651. 0.0352, -0.0631, 0.5460,
  66652. -0.4776, 0.2847, -0.0271
  66653. ];
  66654. var samplesFactor = 1.0 / numSamples;
  66655. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  66656. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  66657. "area", "fallOff", "base", "range", "viewport"
  66658. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  66659. this._ssaoPostProcess.onApply = function (effect) {
  66660. if (_this._firstUpdate) {
  66661. effect.setArray3("sampleSphere", sampleSphere);
  66662. effect.setFloat("samplesFactor", samplesFactor);
  66663. effect.setFloat("randTextureTiles", 4.0);
  66664. }
  66665. effect.setFloat("totalStrength", _this.totalStrength);
  66666. effect.setFloat("radius", _this.radius);
  66667. effect.setFloat("area", _this.area);
  66668. effect.setFloat("fallOff", _this.fallOff);
  66669. effect.setFloat("base", _this.base);
  66670. effect.setTexture("textureSampler", _this._depthTexture);
  66671. effect.setTexture("randomSampler", _this._randomTexture);
  66672. };
  66673. };
  66674. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  66675. var _this = this;
  66676. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66677. this._ssaoCombinePostProcess.onApply = function (effect) {
  66678. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  66679. };
  66680. };
  66681. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  66682. var size = 512;
  66683. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  66684. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66685. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66686. var context = this._randomTexture.getContext();
  66687. var rand = function (min, max) {
  66688. return Math.random() * (max - min) + min;
  66689. };
  66690. var randVector = BABYLON.Vector3.Zero();
  66691. for (var x = 0; x < size; x++) {
  66692. for (var y = 0; y < size; y++) {
  66693. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  66694. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  66695. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  66696. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  66697. context.fillRect(x, y, 1, 1);
  66698. }
  66699. }
  66700. this._randomTexture.update(false);
  66701. };
  66702. __decorate([
  66703. BABYLON.serialize()
  66704. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  66705. __decorate([
  66706. BABYLON.serialize()
  66707. ], SSAORenderingPipeline.prototype, "radius", void 0);
  66708. __decorate([
  66709. BABYLON.serialize()
  66710. ], SSAORenderingPipeline.prototype, "area", void 0);
  66711. __decorate([
  66712. BABYLON.serialize()
  66713. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  66714. __decorate([
  66715. BABYLON.serialize()
  66716. ], SSAORenderingPipeline.prototype, "base", void 0);
  66717. return SSAORenderingPipeline;
  66718. }(BABYLON.PostProcessRenderPipeline));
  66719. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  66720. })(BABYLON || (BABYLON = {}));
  66721. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  66722. var BABYLON;
  66723. (function (BABYLON) {
  66724. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  66725. __extends(SSAO2RenderingPipeline, _super);
  66726. /**
  66727. * @constructor
  66728. * @param {string} name - The rendering pipeline name
  66729. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66730. * @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 }
  66731. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66732. */
  66733. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  66734. var _this = _super.call(this, scene.getEngine(), name) || this;
  66735. // Members
  66736. /**
  66737. * The PassPostProcess id in the pipeline that contains the original scene color
  66738. * @type {string}
  66739. */
  66740. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  66741. /**
  66742. * The SSAO PostProcess id in the pipeline
  66743. * @type {string}
  66744. */
  66745. _this.SSAORenderEffect = "SSAORenderEffect";
  66746. /**
  66747. * The horizontal blur PostProcess id in the pipeline
  66748. * @type {string}
  66749. */
  66750. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  66751. /**
  66752. * The vertical blur PostProcess id in the pipeline
  66753. * @type {string}
  66754. */
  66755. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  66756. /**
  66757. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  66758. * @type {string}
  66759. */
  66760. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  66761. /**
  66762. * The output strength of the SSAO post-process. Default value is 1.0.
  66763. * @type {number}
  66764. */
  66765. _this.totalStrength = 1.0;
  66766. /**
  66767. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  66768. * @type {number}
  66769. */
  66770. _this.maxZ = 100.0;
  66771. /**
  66772. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  66773. * @type {number}
  66774. */
  66775. _this.minZAspect = 0.2;
  66776. /**
  66777. * Number of samples used for the SSAO calculations. Default value is 8
  66778. * @type {number}
  66779. */
  66780. _this._samples = 8;
  66781. /**
  66782. * Are we using bilateral blur ?
  66783. * @type {boolean}
  66784. */
  66785. _this._expensiveBlur = true;
  66786. /**
  66787. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  66788. * @type {number}
  66789. */
  66790. _this.radius = 2.0;
  66791. /**
  66792. * The base color of the SSAO post-process
  66793. * The final result is "base + ssao" between [0, 1]
  66794. * @type {number}
  66795. */
  66796. _this.base = 0.1;
  66797. _this._firstUpdate = true;
  66798. _this._scene = scene;
  66799. if (!_this.isSupported) {
  66800. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  66801. return _this;
  66802. }
  66803. var ssaoRatio = ratio.ssaoRatio || ratio;
  66804. var blurRatio = ratio.blurRatio || ratio;
  66805. // Set up assets
  66806. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  66807. _this._createRandomTexture();
  66808. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  66809. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  66810. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  66811. _this._createSSAOPostProcess(1.0);
  66812. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  66813. _this._createSSAOCombinePostProcess(blurRatio);
  66814. // Set up pipeline
  66815. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  66816. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  66817. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  66818. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  66819. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  66820. // Finish
  66821. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66822. if (cameras)
  66823. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66824. return _this;
  66825. }
  66826. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  66827. get: function () {
  66828. return this._samples;
  66829. },
  66830. set: function (n) {
  66831. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  66832. this._samples = n;
  66833. this._sampleSphere = this._generateHemisphere();
  66834. this._firstUpdate = true;
  66835. },
  66836. enumerable: true,
  66837. configurable: true
  66838. });
  66839. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  66840. get: function () {
  66841. return this._expensiveBlur;
  66842. },
  66843. set: function (b) {
  66844. 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"]);
  66845. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  66846. this._expensiveBlur = b;
  66847. this._firstUpdate = true;
  66848. },
  66849. enumerable: true,
  66850. configurable: true
  66851. });
  66852. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  66853. /**
  66854. * Support test.
  66855. * @type {boolean}
  66856. */
  66857. get: function () {
  66858. var engine = BABYLON.Engine.LastCreatedEngine;
  66859. if (!engine) {
  66860. return false;
  66861. }
  66862. return engine.getCaps().drawBuffersExtension;
  66863. },
  66864. enumerable: true,
  66865. configurable: true
  66866. });
  66867. // Public Methods
  66868. /**
  66869. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  66870. */
  66871. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  66872. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  66873. for (var i = 0; i < this._scene.cameras.length; i++) {
  66874. var camera = this._scene.cameras[i];
  66875. this._originalColorPostProcess.dispose(camera);
  66876. this._ssaoPostProcess.dispose(camera);
  66877. this._blurHPostProcess.dispose(camera);
  66878. this._blurVPostProcess.dispose(camera);
  66879. this._ssaoCombinePostProcess.dispose(camera);
  66880. }
  66881. this._randomTexture.dispose();
  66882. if (disableGeometryBufferRenderer)
  66883. this._scene.disableGeometryBufferRenderer();
  66884. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66885. _super.prototype.dispose.call(this);
  66886. };
  66887. // Private Methods
  66888. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  66889. var _this = this;
  66890. this._samplerOffsets = [];
  66891. var expensive = this.expensiveBlur;
  66892. for (var i = -8; i < 8; i++) {
  66893. this._samplerOffsets.push(i * 2 + 0.5);
  66894. }
  66895. 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");
  66896. this._blurHPostProcess.onApply = function (effect) {
  66897. if (!_this._scene.activeCamera) {
  66898. return;
  66899. }
  66900. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  66901. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66902. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66903. effect.setFloat("radius", _this.radius);
  66904. effect.setTexture("depthSampler", _this._depthTexture);
  66905. if (_this._firstUpdate) {
  66906. effect.setArray("samplerOffsets", _this._samplerOffsets);
  66907. }
  66908. };
  66909. 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");
  66910. this._blurVPostProcess.onApply = function (effect) {
  66911. if (!_this._scene.activeCamera) {
  66912. return;
  66913. }
  66914. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  66915. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66916. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66917. effect.setFloat("radius", _this.radius);
  66918. effect.setTexture("depthSampler", _this._depthTexture);
  66919. if (_this._firstUpdate) {
  66920. effect.setArray("samplerOffsets", _this._samplerOffsets);
  66921. _this._firstUpdate = false;
  66922. }
  66923. };
  66924. };
  66925. SSAO2RenderingPipeline.prototype._rebuild = function () {
  66926. this._firstUpdate = true;
  66927. _super.prototype._rebuild.call(this);
  66928. };
  66929. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  66930. var numSamples = this.samples;
  66931. var result = [];
  66932. var vector, scale;
  66933. var rand = function (min, max) {
  66934. return Math.random() * (max - min) + min;
  66935. };
  66936. var i = 0;
  66937. while (i < numSamples) {
  66938. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  66939. vector.normalize();
  66940. scale = i / numSamples;
  66941. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  66942. vector.scaleInPlace(scale);
  66943. result.push(vector.x, vector.y, vector.z);
  66944. i++;
  66945. }
  66946. return result;
  66947. };
  66948. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  66949. var _this = this;
  66950. var numSamples = this.samples;
  66951. this._sampleSphere = this._generateHemisphere();
  66952. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  66953. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  66954. "base", "range", "projection", "near", "far", "texelSize",
  66955. "xViewport", "yViewport", "maxZ", "minZAspect"
  66956. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  66957. this._ssaoPostProcess.onApply = function (effect) {
  66958. if (_this._firstUpdate) {
  66959. effect.setArray3("sampleSphere", _this._sampleSphere);
  66960. effect.setFloat("randTextureTiles", 4.0);
  66961. }
  66962. if (!_this._scene.activeCamera) {
  66963. return;
  66964. }
  66965. effect.setFloat("samplesFactor", 1 / _this.samples);
  66966. effect.setFloat("totalStrength", _this.totalStrength);
  66967. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  66968. effect.setFloat("radius", _this.radius);
  66969. effect.setFloat("maxZ", _this.maxZ);
  66970. effect.setFloat("minZAspect", _this.minZAspect);
  66971. effect.setFloat("base", _this.base);
  66972. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66973. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66974. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  66975. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  66976. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  66977. effect.setTexture("textureSampler", _this._depthTexture);
  66978. effect.setTexture("normalSampler", _this._normalTexture);
  66979. effect.setTexture("randomSampler", _this._randomTexture);
  66980. };
  66981. };
  66982. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  66983. var _this = this;
  66984. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66985. this._ssaoCombinePostProcess.onApply = function (effect) {
  66986. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  66987. };
  66988. };
  66989. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  66990. var size = 512;
  66991. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  66992. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66993. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66994. var context = this._randomTexture.getContext();
  66995. var rand = function (min, max) {
  66996. return Math.random() * (max - min) + min;
  66997. };
  66998. var randVector = BABYLON.Vector3.Zero();
  66999. for (var x = 0; x < size; x++) {
  67000. for (var y = 0; y < size; y++) {
  67001. randVector.x = rand(0.0, 1.0);
  67002. randVector.y = rand(0.0, 1.0);
  67003. randVector.z = 0.0;
  67004. randVector.normalize();
  67005. randVector.scaleInPlace(255);
  67006. randVector.x = Math.floor(randVector.x);
  67007. randVector.y = Math.floor(randVector.y);
  67008. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  67009. context.fillRect(x, y, 1, 1);
  67010. }
  67011. }
  67012. this._randomTexture.update(false);
  67013. };
  67014. __decorate([
  67015. BABYLON.serialize()
  67016. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  67017. __decorate([
  67018. BABYLON.serialize()
  67019. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  67020. __decorate([
  67021. BABYLON.serialize()
  67022. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  67023. __decorate([
  67024. BABYLON.serialize("samples")
  67025. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  67026. __decorate([
  67027. BABYLON.serialize("expensiveBlur")
  67028. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  67029. __decorate([
  67030. BABYLON.serialize()
  67031. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  67032. __decorate([
  67033. BABYLON.serialize()
  67034. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  67035. return SSAO2RenderingPipeline;
  67036. }(BABYLON.PostProcessRenderPipeline));
  67037. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  67038. })(BABYLON || (BABYLON = {}));
  67039. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  67040. // BABYLON.JS Chromatic Aberration GLSL Shader
  67041. // Author: Olivier Guyot
  67042. // Separates very slightly R, G and B colors on the edges of the screen
  67043. // Inspired by Francois Tarlier & Martins Upitis
  67044. var BABYLON;
  67045. (function (BABYLON) {
  67046. var LensRenderingPipeline = /** @class */ (function (_super) {
  67047. __extends(LensRenderingPipeline, _super);
  67048. /**
  67049. * @constructor
  67050. *
  67051. * Effect parameters are as follow:
  67052. * {
  67053. * chromatic_aberration: number; // from 0 to x (1 for realism)
  67054. * edge_blur: number; // from 0 to x (1 for realism)
  67055. * distortion: number; // from 0 to x (1 for realism)
  67056. * grain_amount: number; // from 0 to 1
  67057. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  67058. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  67059. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  67060. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  67061. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  67062. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  67063. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  67064. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  67065. * }
  67066. * Note: if an effect parameter is unset, effect is disabled
  67067. *
  67068. * @param {string} name - The rendering pipeline name
  67069. * @param {object} parameters - An object containing all parameters (see above)
  67070. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67071. * @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)
  67072. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67073. */
  67074. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  67075. if (ratio === void 0) { ratio = 1.0; }
  67076. var _this = _super.call(this, scene.getEngine(), name) || this;
  67077. // Lens effects can be of the following:
  67078. // - chromatic aberration (slight shift of RGB colors)
  67079. // - blur on the edge of the lens
  67080. // - lens distortion
  67081. // - depth-of-field blur & highlights enhancing
  67082. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  67083. // - grain effect (noise or custom texture)
  67084. // Two additional texture samplers are needed:
  67085. // - depth map (for depth-of-field)
  67086. // - grain texture
  67087. /**
  67088. * The chromatic aberration PostProcess id in the pipeline
  67089. * @type {string}
  67090. */
  67091. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  67092. /**
  67093. * The highlights enhancing PostProcess id in the pipeline
  67094. * @type {string}
  67095. */
  67096. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  67097. /**
  67098. * The depth-of-field PostProcess id in the pipeline
  67099. * @type {string}
  67100. */
  67101. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  67102. _this._scene = scene;
  67103. // Fetch texture samplers
  67104. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  67105. if (parameters.grain_texture) {
  67106. _this._grainTexture = parameters.grain_texture;
  67107. }
  67108. else {
  67109. _this._createGrainTexture();
  67110. }
  67111. // save parameters
  67112. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  67113. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  67114. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  67115. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  67116. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  67117. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  67118. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  67119. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  67120. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  67121. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  67122. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  67123. // Create effects
  67124. _this._createChromaticAberrationPostProcess(ratio);
  67125. _this._createHighlightsPostProcess(ratio);
  67126. _this._createDepthOfFieldPostProcess(ratio / 4);
  67127. // Set up pipeline
  67128. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  67129. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  67130. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  67131. if (_this._highlightsGain === -1) {
  67132. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  67133. }
  67134. // Finish
  67135. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67136. if (cameras) {
  67137. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  67138. }
  67139. return _this;
  67140. }
  67141. // public methods (self explanatory)
  67142. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  67143. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  67144. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  67145. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  67146. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  67147. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  67148. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  67149. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  67150. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  67151. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  67152. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  67153. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  67154. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  67155. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  67156. };
  67157. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  67158. this._highlightsPostProcess.updateEffect();
  67159. };
  67160. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  67161. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  67162. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  67163. this._highlightsGain = amount;
  67164. };
  67165. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  67166. if (this._highlightsGain === -1) {
  67167. this._highlightsGain = 1.0;
  67168. }
  67169. this._highlightsThreshold = amount;
  67170. };
  67171. LensRenderingPipeline.prototype.disableHighlights = function () {
  67172. this._highlightsGain = -1;
  67173. };
  67174. /**
  67175. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  67176. */
  67177. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  67178. if (disableDepthRender === void 0) { disableDepthRender = false; }
  67179. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67180. this._chromaticAberrationPostProcess = null;
  67181. this._highlightsPostProcess = null;
  67182. this._depthOfFieldPostProcess = null;
  67183. this._grainTexture.dispose();
  67184. if (disableDepthRender)
  67185. this._scene.disableDepthRenderer();
  67186. };
  67187. // colors shifting and distortion
  67188. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  67189. var _this = this;
  67190. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  67191. [], // samplers
  67192. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67193. this._chromaticAberrationPostProcess.onApply = function (effect) {
  67194. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  67195. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67196. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67197. };
  67198. };
  67199. // highlights enhancing
  67200. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  67201. var _this = this;
  67202. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  67203. [], // samplers
  67204. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  67205. this._highlightsPostProcess.onApply = function (effect) {
  67206. effect.setFloat('gain', _this._highlightsGain);
  67207. effect.setFloat('threshold', _this._highlightsThreshold);
  67208. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  67209. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67210. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67211. };
  67212. };
  67213. // colors shifting and distortion
  67214. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  67215. var _this = this;
  67216. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  67217. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  67218. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  67219. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67220. this._depthOfFieldPostProcess.onApply = function (effect) {
  67221. effect.setTexture("depthSampler", _this._depthTexture);
  67222. effect.setTexture("grainSampler", _this._grainTexture);
  67223. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  67224. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  67225. effect.setFloat('grain_amount', _this._grainAmount);
  67226. effect.setBool('blur_noise', _this._blurNoise);
  67227. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67228. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67229. effect.setFloat('distortion', _this._distortion);
  67230. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  67231. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  67232. effect.setFloat('aperture', _this._dofAperture);
  67233. effect.setFloat('darken', _this._dofDarken);
  67234. effect.setFloat('edge_blur', _this._edgeBlur);
  67235. effect.setBool('highlights', (_this._highlightsGain !== -1));
  67236. if (_this._scene.activeCamera) {
  67237. effect.setFloat('near', _this._scene.activeCamera.minZ);
  67238. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  67239. }
  67240. };
  67241. };
  67242. // creates a black and white random noise texture, 512x512
  67243. LensRenderingPipeline.prototype._createGrainTexture = function () {
  67244. var size = 512;
  67245. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67246. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67247. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67248. var context = this._grainTexture.getContext();
  67249. var rand = function (min, max) {
  67250. return Math.random() * (max - min) + min;
  67251. };
  67252. var value;
  67253. for (var x = 0; x < size; x++) {
  67254. for (var y = 0; y < size; y++) {
  67255. value = Math.floor(rand(0.42, 0.58) * 255);
  67256. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  67257. context.fillRect(x, y, 1, 1);
  67258. }
  67259. }
  67260. this._grainTexture.update(false);
  67261. };
  67262. return LensRenderingPipeline;
  67263. }(BABYLON.PostProcessRenderPipeline));
  67264. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  67265. })(BABYLON || (BABYLON = {}));
  67266. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  67267. var BABYLON;
  67268. (function (BABYLON) {
  67269. var StandardRenderingPipeline = /** @class */ (function (_super) {
  67270. __extends(StandardRenderingPipeline, _super);
  67271. /**
  67272. * @constructor
  67273. * @param {string} name - The rendering pipeline name
  67274. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67275. * @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)
  67276. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  67277. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67278. */
  67279. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  67280. if (originalPostProcess === void 0) { originalPostProcess = null; }
  67281. var _this = _super.call(this, scene.getEngine(), name) || this;
  67282. _this.downSampleX4PostProcess = null;
  67283. _this.brightPassPostProcess = null;
  67284. _this.blurHPostProcesses = [];
  67285. _this.blurVPostProcesses = [];
  67286. _this.textureAdderPostProcess = null;
  67287. _this.volumetricLightPostProcess = null;
  67288. _this.volumetricLightSmoothXPostProcess = null;
  67289. _this.volumetricLightSmoothYPostProcess = null;
  67290. _this.volumetricLightMergePostProces = null;
  67291. _this.volumetricLightFinalPostProcess = null;
  67292. _this.luminancePostProcess = null;
  67293. _this.luminanceDownSamplePostProcesses = [];
  67294. _this.hdrPostProcess = null;
  67295. _this.textureAdderFinalPostProcess = null;
  67296. _this.lensFlareFinalPostProcess = null;
  67297. _this.hdrFinalPostProcess = null;
  67298. _this.lensFlarePostProcess = null;
  67299. _this.lensFlareComposePostProcess = null;
  67300. _this.motionBlurPostProcess = null;
  67301. _this.depthOfFieldPostProcess = null;
  67302. // Values
  67303. _this.brightThreshold = 1.0;
  67304. _this.blurWidth = 512.0;
  67305. _this.horizontalBlur = false;
  67306. _this.exposure = 1.0;
  67307. _this.lensTexture = null;
  67308. _this.volumetricLightCoefficient = 0.2;
  67309. _this.volumetricLightPower = 4.0;
  67310. _this.volumetricLightBlurScale = 64.0;
  67311. _this.sourceLight = null;
  67312. _this.hdrMinimumLuminance = 1.0;
  67313. _this.hdrDecreaseRate = 0.5;
  67314. _this.hdrIncreaseRate = 0.5;
  67315. _this.lensColorTexture = null;
  67316. _this.lensFlareStrength = 20.0;
  67317. _this.lensFlareGhostDispersal = 1.4;
  67318. _this.lensFlareHaloWidth = 0.7;
  67319. _this.lensFlareDistortionStrength = 16.0;
  67320. _this.lensStarTexture = null;
  67321. _this.lensFlareDirtTexture = null;
  67322. _this.depthOfFieldDistance = 10.0;
  67323. _this.depthOfFieldBlurWidth = 64.0;
  67324. _this.motionStrength = 1.0;
  67325. // IAnimatable
  67326. _this.animations = [];
  67327. _this._currentDepthOfFieldSource = null;
  67328. _this._hdrCurrentLuminance = 1.0;
  67329. // Getters and setters
  67330. _this._bloomEnabled = true;
  67331. _this._depthOfFieldEnabled = false;
  67332. _this._vlsEnabled = false;
  67333. _this._lensFlareEnabled = false;
  67334. _this._hdrEnabled = false;
  67335. _this._motionBlurEnabled = false;
  67336. _this._motionBlurSamples = 64.0;
  67337. _this._volumetricLightStepsCount = 50.0;
  67338. _this._cameras = cameras || [];
  67339. // Initialize
  67340. _this._scene = scene;
  67341. _this._basePostProcess = originalPostProcess;
  67342. _this._ratio = ratio;
  67343. // Misc
  67344. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67345. // Finish
  67346. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67347. _this._buildPipeline();
  67348. return _this;
  67349. }
  67350. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  67351. get: function () {
  67352. return this._bloomEnabled;
  67353. },
  67354. set: function (enabled) {
  67355. if (this._bloomEnabled === enabled) {
  67356. return;
  67357. }
  67358. this._bloomEnabled = enabled;
  67359. this._buildPipeline();
  67360. },
  67361. enumerable: true,
  67362. configurable: true
  67363. });
  67364. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  67365. get: function () {
  67366. return this._depthOfFieldEnabled;
  67367. },
  67368. set: function (enabled) {
  67369. if (this._depthOfFieldEnabled === enabled) {
  67370. return;
  67371. }
  67372. this._depthOfFieldEnabled = enabled;
  67373. this._buildPipeline();
  67374. },
  67375. enumerable: true,
  67376. configurable: true
  67377. });
  67378. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  67379. get: function () {
  67380. return this._lensFlareEnabled;
  67381. },
  67382. set: function (enabled) {
  67383. if (this._lensFlareEnabled === enabled) {
  67384. return;
  67385. }
  67386. this._lensFlareEnabled = enabled;
  67387. this._buildPipeline();
  67388. },
  67389. enumerable: true,
  67390. configurable: true
  67391. });
  67392. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  67393. get: function () {
  67394. return this._hdrEnabled;
  67395. },
  67396. set: function (enabled) {
  67397. if (this._hdrEnabled === enabled) {
  67398. return;
  67399. }
  67400. this._hdrEnabled = enabled;
  67401. this._buildPipeline();
  67402. },
  67403. enumerable: true,
  67404. configurable: true
  67405. });
  67406. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  67407. get: function () {
  67408. return this._vlsEnabled;
  67409. },
  67410. set: function (enabled) {
  67411. if (this._vlsEnabled === enabled) {
  67412. return;
  67413. }
  67414. if (enabled) {
  67415. var geometry = this._scene.enableGeometryBufferRenderer();
  67416. if (!geometry) {
  67417. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  67418. return;
  67419. }
  67420. }
  67421. this._vlsEnabled = enabled;
  67422. this._buildPipeline();
  67423. },
  67424. enumerable: true,
  67425. configurable: true
  67426. });
  67427. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  67428. get: function () {
  67429. return this._motionBlurEnabled;
  67430. },
  67431. set: function (enabled) {
  67432. if (this._motionBlurEnabled === enabled) {
  67433. return;
  67434. }
  67435. this._motionBlurEnabled = enabled;
  67436. this._buildPipeline();
  67437. },
  67438. enumerable: true,
  67439. configurable: true
  67440. });
  67441. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  67442. get: function () {
  67443. return this._volumetricLightStepsCount;
  67444. },
  67445. set: function (count) {
  67446. if (this.volumetricLightPostProcess) {
  67447. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  67448. }
  67449. this._volumetricLightStepsCount = count;
  67450. },
  67451. enumerable: true,
  67452. configurable: true
  67453. });
  67454. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  67455. get: function () {
  67456. return this._motionBlurSamples;
  67457. },
  67458. set: function (samples) {
  67459. if (this.motionBlurPostProcess) {
  67460. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  67461. }
  67462. this._motionBlurSamples = samples;
  67463. },
  67464. enumerable: true,
  67465. configurable: true
  67466. });
  67467. StandardRenderingPipeline.prototype._buildPipeline = function () {
  67468. var _this = this;
  67469. var ratio = this._ratio;
  67470. var scene = this._scene;
  67471. this._disposePostProcesses();
  67472. this._reset();
  67473. // Create pass post-process
  67474. if (!this._basePostProcess) {
  67475. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  67476. this.originalPostProcess.onApply = function (effect) {
  67477. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  67478. };
  67479. }
  67480. else {
  67481. this.originalPostProcess = this._basePostProcess;
  67482. }
  67483. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  67484. this._currentDepthOfFieldSource = this.originalPostProcess;
  67485. if (this._vlsEnabled) {
  67486. // Create volumetric light
  67487. this._createVolumetricLightPostProcess(scene, ratio);
  67488. // Create volumetric light final post-process
  67489. 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);
  67490. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  67491. }
  67492. if (this._bloomEnabled) {
  67493. // Create down sample X4 post-process
  67494. this._createDownSampleX4PostProcess(scene, ratio / 2);
  67495. // Create bright pass post-process
  67496. this._createBrightPassPostProcess(scene, ratio / 2);
  67497. // Create gaussian blur post-processes (down sampling blurs)
  67498. this._createBlurPostProcesses(scene, ratio / 4, 1);
  67499. // Create texture adder post-process
  67500. this._createTextureAdderPostProcess(scene, ratio);
  67501. // Create depth-of-field source post-process
  67502. 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);
  67503. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  67504. }
  67505. if (this._lensFlareEnabled) {
  67506. // Create lens flare post-process
  67507. this._createLensFlarePostProcess(scene, ratio);
  67508. // Create depth-of-field source post-process post lens-flare and disable it now
  67509. 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);
  67510. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  67511. }
  67512. if (this._hdrEnabled) {
  67513. // Create luminance
  67514. this._createLuminancePostProcesses(scene, this._floatTextureType);
  67515. // Create HDR
  67516. this._createHdrPostProcess(scene, ratio);
  67517. // Create depth-of-field source post-process post hdr and disable it now
  67518. 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);
  67519. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  67520. }
  67521. if (this._depthOfFieldEnabled) {
  67522. // Create gaussian blur used by depth-of-field
  67523. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  67524. // Create depth-of-field post-process
  67525. this._createDepthOfFieldPostProcess(scene, ratio);
  67526. }
  67527. if (this._motionBlurEnabled) {
  67528. // Create motion blur post-process
  67529. this._createMotionBlurPostProcess(scene, ratio);
  67530. }
  67531. if (this._cameras !== null) {
  67532. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  67533. }
  67534. };
  67535. // Down Sample X4 Post-Processs
  67536. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  67537. var _this = this;
  67538. var downSampleX4Offsets = new Array(32);
  67539. 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);
  67540. this.downSampleX4PostProcess.onApply = function (effect) {
  67541. var id = 0;
  67542. var width = _this.downSampleX4PostProcess.width;
  67543. var height = _this.downSampleX4PostProcess.height;
  67544. for (var i = -2; i < 2; i++) {
  67545. for (var j = -2; j < 2; j++) {
  67546. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  67547. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  67548. id += 2;
  67549. }
  67550. }
  67551. effect.setArray2("dsOffsets", downSampleX4Offsets);
  67552. };
  67553. // Add to pipeline
  67554. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  67555. };
  67556. // Brightpass Post-Process
  67557. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  67558. var _this = this;
  67559. var brightOffsets = new Array(8);
  67560. 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);
  67561. this.brightPassPostProcess.onApply = function (effect) {
  67562. var sU = (1.0 / _this.brightPassPostProcess.width);
  67563. var sV = (1.0 / _this.brightPassPostProcess.height);
  67564. brightOffsets[0] = -0.5 * sU;
  67565. brightOffsets[1] = 0.5 * sV;
  67566. brightOffsets[2] = 0.5 * sU;
  67567. brightOffsets[3] = 0.5 * sV;
  67568. brightOffsets[4] = -0.5 * sU;
  67569. brightOffsets[5] = -0.5 * sV;
  67570. brightOffsets[6] = 0.5 * sU;
  67571. brightOffsets[7] = -0.5 * sV;
  67572. effect.setArray2("dsOffsets", brightOffsets);
  67573. effect.setFloat("brightThreshold", _this.brightThreshold);
  67574. };
  67575. // Add to pipeline
  67576. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  67577. };
  67578. // Create blur H&V post-processes
  67579. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  67580. var _this = this;
  67581. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  67582. var engine = scene.getEngine();
  67583. 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);
  67584. 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);
  67585. blurX.onActivateObservable.add(function () {
  67586. var dw = blurX.width / engine.getRenderWidth();
  67587. blurX.kernel = _this[blurWidthKey] * dw;
  67588. });
  67589. blurY.onActivateObservable.add(function () {
  67590. var dw = blurY.height / engine.getRenderHeight();
  67591. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  67592. });
  67593. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  67594. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  67595. this.blurHPostProcesses.push(blurX);
  67596. this.blurVPostProcesses.push(blurY);
  67597. };
  67598. // Create texture adder post-process
  67599. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  67600. var _this = this;
  67601. 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);
  67602. this.textureAdderPostProcess.onApply = function (effect) {
  67603. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  67604. effect.setTexture("lensSampler", _this.lensTexture);
  67605. effect.setFloat("exposure", _this.exposure);
  67606. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  67607. };
  67608. // Add to pipeline
  67609. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  67610. };
  67611. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  67612. var _this = this;
  67613. var geometryRenderer = scene.enableGeometryBufferRenderer();
  67614. geometryRenderer.enablePosition = true;
  67615. var geometry = geometryRenderer.getGBuffer();
  67616. // Base post-process
  67617. 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));
  67618. var depthValues = BABYLON.Vector2.Zero();
  67619. this.volumetricLightPostProcess.onApply = function (effect) {
  67620. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  67621. var generator = _this.sourceLight.getShadowGenerator();
  67622. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  67623. effect.setTexture("positionSampler", geometry.textures[2]);
  67624. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  67625. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  67626. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  67627. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  67628. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  67629. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  67630. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  67631. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  67632. effect.setVector2("depthValues", depthValues);
  67633. }
  67634. };
  67635. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  67636. // Smooth
  67637. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  67638. // Merge
  67639. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  67640. this.volumetricLightMergePostProces.onApply = function (effect) {
  67641. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  67642. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  67643. };
  67644. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  67645. };
  67646. // Create luminance
  67647. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  67648. var _this = this;
  67649. // Create luminance
  67650. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  67651. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  67652. var offsets = [];
  67653. this.luminancePostProcess.onApply = function (effect) {
  67654. var sU = (1.0 / _this.luminancePostProcess.width);
  67655. var sV = (1.0 / _this.luminancePostProcess.height);
  67656. offsets[0] = -0.5 * sU;
  67657. offsets[1] = 0.5 * sV;
  67658. offsets[2] = 0.5 * sU;
  67659. offsets[3] = 0.5 * sV;
  67660. offsets[4] = -0.5 * sU;
  67661. offsets[5] = -0.5 * sV;
  67662. offsets[6] = 0.5 * sU;
  67663. offsets[7] = -0.5 * sV;
  67664. effect.setArray2("lumOffsets", offsets);
  67665. };
  67666. // Add to pipeline
  67667. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  67668. // Create down sample luminance
  67669. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  67670. var size = Math.pow(3, i);
  67671. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  67672. if (i === 0) {
  67673. defines += "#define FINAL_DOWN_SAMPLER";
  67674. }
  67675. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  67676. this.luminanceDownSamplePostProcesses.push(postProcess);
  67677. }
  67678. // Create callbacks and add effects
  67679. var lastLuminance = this.luminancePostProcess;
  67680. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  67681. var downSampleOffsets = new Array(18);
  67682. pp.onApply = function (effect) {
  67683. if (!lastLuminance) {
  67684. return;
  67685. }
  67686. var id = 0;
  67687. for (var x = -1; x < 2; x++) {
  67688. for (var y = -1; y < 2; y++) {
  67689. downSampleOffsets[id] = x / lastLuminance.width;
  67690. downSampleOffsets[id + 1] = y / lastLuminance.height;
  67691. id += 2;
  67692. }
  67693. }
  67694. effect.setArray2("dsOffsets", downSampleOffsets);
  67695. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  67696. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  67697. lastLuminance = _this.luminancePostProcess;
  67698. }
  67699. else {
  67700. lastLuminance = pp;
  67701. }
  67702. };
  67703. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  67704. pp.onAfterRender = function (effect) {
  67705. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  67706. 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);
  67707. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  67708. };
  67709. }
  67710. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  67711. });
  67712. };
  67713. // Create HDR post-process
  67714. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  67715. var _this = this;
  67716. 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);
  67717. var outputLiminance = 1;
  67718. var time = 0;
  67719. var lastTime = 0;
  67720. this.hdrPostProcess.onApply = function (effect) {
  67721. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  67722. time += scene.getEngine().getDeltaTime();
  67723. if (outputLiminance < 0) {
  67724. outputLiminance = _this._hdrCurrentLuminance;
  67725. }
  67726. else {
  67727. var dt = (lastTime - time) / 1000.0;
  67728. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  67729. outputLiminance += _this.hdrDecreaseRate * dt;
  67730. }
  67731. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  67732. outputLiminance -= _this.hdrIncreaseRate * dt;
  67733. }
  67734. else {
  67735. outputLiminance = _this._hdrCurrentLuminance;
  67736. }
  67737. }
  67738. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  67739. effect.setFloat("averageLuminance", outputLiminance);
  67740. lastTime = time;
  67741. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  67742. };
  67743. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  67744. };
  67745. // Create lens flare post-process
  67746. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  67747. var _this = this;
  67748. 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);
  67749. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  67750. this._createBlurPostProcesses(scene, ratio / 4, 2);
  67751. 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);
  67752. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  67753. var resolution = new BABYLON.Vector2(0, 0);
  67754. // Lens flare
  67755. this.lensFlarePostProcess.onApply = function (effect) {
  67756. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  67757. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  67758. effect.setFloat("strength", _this.lensFlareStrength);
  67759. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  67760. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  67761. // Shift
  67762. resolution.x = _this.lensFlarePostProcess.width;
  67763. resolution.y = _this.lensFlarePostProcess.height;
  67764. effect.setVector2("resolution", resolution);
  67765. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  67766. };
  67767. // Compose
  67768. 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);
  67769. 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);
  67770. this.lensFlareComposePostProcess.onApply = function (effect) {
  67771. if (!_this._scene.activeCamera) {
  67772. return;
  67773. }
  67774. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  67775. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  67776. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  67777. // Lens start rotation matrix
  67778. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  67779. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  67780. 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));
  67781. camRot *= 4.0;
  67782. 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);
  67783. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  67784. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  67785. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  67786. };
  67787. };
  67788. // Create depth-of-field post-process
  67789. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  67790. var _this = this;
  67791. 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);
  67792. this.depthOfFieldPostProcess.onApply = function (effect) {
  67793. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  67794. effect.setTexture("depthSampler", _this._getDepthTexture());
  67795. effect.setFloat("distance", _this.depthOfFieldDistance);
  67796. };
  67797. // Add to pipeline
  67798. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  67799. };
  67800. // Create motion blur post-process
  67801. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  67802. var _this = this;
  67803. 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);
  67804. var motionScale = 0;
  67805. var prevViewProjection = BABYLON.Matrix.Identity();
  67806. var invViewProjection = BABYLON.Matrix.Identity();
  67807. var viewProjection = BABYLON.Matrix.Identity();
  67808. var screenSize = BABYLON.Vector2.Zero();
  67809. this.motionBlurPostProcess.onApply = function (effect) {
  67810. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  67811. viewProjection.invertToRef(invViewProjection);
  67812. effect.setMatrix("inverseViewProjection", invViewProjection);
  67813. effect.setMatrix("prevViewProjection", prevViewProjection);
  67814. prevViewProjection = viewProjection;
  67815. screenSize.x = _this.motionBlurPostProcess.width;
  67816. screenSize.y = _this.motionBlurPostProcess.height;
  67817. effect.setVector2("screenSize", screenSize);
  67818. motionScale = scene.getEngine().getFps() / 60.0;
  67819. effect.setFloat("motionScale", motionScale);
  67820. effect.setFloat("motionStrength", _this.motionStrength);
  67821. effect.setTexture("depthSampler", _this._getDepthTexture());
  67822. };
  67823. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  67824. };
  67825. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  67826. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  67827. var renderer = this._scene.enableGeometryBufferRenderer();
  67828. return renderer.getGBuffer().textures[0];
  67829. }
  67830. return this._scene.enableDepthRenderer().getDepthMap();
  67831. };
  67832. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  67833. for (var i = 0; i < this._cameras.length; i++) {
  67834. var camera = this._cameras[i];
  67835. if (this.originalPostProcess) {
  67836. this.originalPostProcess.dispose(camera);
  67837. }
  67838. if (this.downSampleX4PostProcess) {
  67839. this.downSampleX4PostProcess.dispose(camera);
  67840. }
  67841. if (this.brightPassPostProcess) {
  67842. this.brightPassPostProcess.dispose(camera);
  67843. }
  67844. if (this.textureAdderPostProcess) {
  67845. this.textureAdderPostProcess.dispose(camera);
  67846. }
  67847. if (this.textureAdderFinalPostProcess) {
  67848. this.textureAdderFinalPostProcess.dispose(camera);
  67849. }
  67850. if (this.volumetricLightPostProcess) {
  67851. this.volumetricLightPostProcess.dispose(camera);
  67852. }
  67853. if (this.volumetricLightSmoothXPostProcess) {
  67854. this.volumetricLightSmoothXPostProcess.dispose(camera);
  67855. }
  67856. if (this.volumetricLightSmoothYPostProcess) {
  67857. this.volumetricLightSmoothYPostProcess.dispose(camera);
  67858. }
  67859. if (this.volumetricLightMergePostProces) {
  67860. this.volumetricLightMergePostProces.dispose(camera);
  67861. }
  67862. if (this.volumetricLightFinalPostProcess) {
  67863. this.volumetricLightFinalPostProcess.dispose(camera);
  67864. }
  67865. if (this.lensFlarePostProcess) {
  67866. this.lensFlarePostProcess.dispose(camera);
  67867. }
  67868. if (this.lensFlareComposePostProcess) {
  67869. this.lensFlareComposePostProcess.dispose(camera);
  67870. }
  67871. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  67872. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  67873. }
  67874. if (this.luminancePostProcess) {
  67875. this.luminancePostProcess.dispose(camera);
  67876. }
  67877. if (this.hdrPostProcess) {
  67878. this.hdrPostProcess.dispose(camera);
  67879. }
  67880. if (this.hdrFinalPostProcess) {
  67881. this.hdrFinalPostProcess.dispose(camera);
  67882. }
  67883. if (this.depthOfFieldPostProcess) {
  67884. this.depthOfFieldPostProcess.dispose(camera);
  67885. }
  67886. if (this.motionBlurPostProcess) {
  67887. this.motionBlurPostProcess.dispose(camera);
  67888. }
  67889. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  67890. this.blurHPostProcesses[j].dispose(camera);
  67891. }
  67892. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  67893. this.blurVPostProcesses[j].dispose(camera);
  67894. }
  67895. }
  67896. this.originalPostProcess = null;
  67897. this.downSampleX4PostProcess = null;
  67898. this.brightPassPostProcess = null;
  67899. this.textureAdderPostProcess = null;
  67900. this.textureAdderFinalPostProcess = null;
  67901. this.volumetricLightPostProcess = null;
  67902. this.volumetricLightSmoothXPostProcess = null;
  67903. this.volumetricLightSmoothYPostProcess = null;
  67904. this.volumetricLightMergePostProces = null;
  67905. this.volumetricLightFinalPostProcess = null;
  67906. this.lensFlarePostProcess = null;
  67907. this.lensFlareComposePostProcess = null;
  67908. this.luminancePostProcess = null;
  67909. this.hdrPostProcess = null;
  67910. this.hdrFinalPostProcess = null;
  67911. this.depthOfFieldPostProcess = null;
  67912. this.motionBlurPostProcess = null;
  67913. this.luminanceDownSamplePostProcesses = [];
  67914. this.blurHPostProcesses = [];
  67915. this.blurVPostProcesses = [];
  67916. };
  67917. // Dispose
  67918. StandardRenderingPipeline.prototype.dispose = function () {
  67919. this._disposePostProcesses();
  67920. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  67921. _super.prototype.dispose.call(this);
  67922. };
  67923. // Serialize rendering pipeline
  67924. StandardRenderingPipeline.prototype.serialize = function () {
  67925. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  67926. serializationObject.customType = "StandardRenderingPipeline";
  67927. return serializationObject;
  67928. };
  67929. /**
  67930. * Static members
  67931. */
  67932. // Parse serialized pipeline
  67933. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  67934. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  67935. };
  67936. // Luminance steps
  67937. StandardRenderingPipeline.LuminanceSteps = 6;
  67938. __decorate([
  67939. BABYLON.serialize()
  67940. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  67941. __decorate([
  67942. BABYLON.serialize()
  67943. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  67944. __decorate([
  67945. BABYLON.serialize()
  67946. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  67947. __decorate([
  67948. BABYLON.serialize()
  67949. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  67950. __decorate([
  67951. BABYLON.serializeAsTexture("lensTexture")
  67952. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  67953. __decorate([
  67954. BABYLON.serialize()
  67955. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  67956. __decorate([
  67957. BABYLON.serialize()
  67958. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  67959. __decorate([
  67960. BABYLON.serialize()
  67961. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  67962. __decorate([
  67963. BABYLON.serialize()
  67964. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  67965. __decorate([
  67966. BABYLON.serialize()
  67967. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  67968. __decorate([
  67969. BABYLON.serialize()
  67970. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  67971. __decorate([
  67972. BABYLON.serializeAsTexture("lensColorTexture")
  67973. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  67974. __decorate([
  67975. BABYLON.serialize()
  67976. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  67977. __decorate([
  67978. BABYLON.serialize()
  67979. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  67980. __decorate([
  67981. BABYLON.serialize()
  67982. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  67983. __decorate([
  67984. BABYLON.serialize()
  67985. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  67986. __decorate([
  67987. BABYLON.serializeAsTexture("lensStarTexture")
  67988. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  67989. __decorate([
  67990. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  67991. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  67992. __decorate([
  67993. BABYLON.serialize()
  67994. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  67995. __decorate([
  67996. BABYLON.serialize()
  67997. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  67998. __decorate([
  67999. BABYLON.serialize()
  68000. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  68001. __decorate([
  68002. BABYLON.serialize()
  68003. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  68004. __decorate([
  68005. BABYLON.serialize()
  68006. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  68007. __decorate([
  68008. BABYLON.serialize()
  68009. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  68010. __decorate([
  68011. BABYLON.serialize()
  68012. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  68013. __decorate([
  68014. BABYLON.serialize()
  68015. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  68016. __decorate([
  68017. BABYLON.serialize()
  68018. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  68019. __decorate([
  68020. BABYLON.serialize()
  68021. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  68022. __decorate([
  68023. BABYLON.serialize()
  68024. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  68025. __decorate([
  68026. BABYLON.serialize()
  68027. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  68028. return StandardRenderingPipeline;
  68029. }(BABYLON.PostProcessRenderPipeline));
  68030. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  68031. })(BABYLON || (BABYLON = {}));
  68032. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  68033. var BABYLON;
  68034. (function (BABYLON) {
  68035. var FxaaPostProcess = /** @class */ (function (_super) {
  68036. __extends(FxaaPostProcess, _super);
  68037. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  68038. if (camera === void 0) { camera = null; }
  68039. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68040. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  68041. _this.onApplyObservable.add(function (effect) {
  68042. var texelSize = _this.texelSize;
  68043. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  68044. });
  68045. return _this;
  68046. }
  68047. return FxaaPostProcess;
  68048. }(BABYLON.PostProcess));
  68049. BABYLON.FxaaPostProcess = FxaaPostProcess;
  68050. })(BABYLON || (BABYLON = {}));
  68051. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  68052. var BABYLON;
  68053. (function (BABYLON) {
  68054. /**
  68055. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  68056. */
  68057. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  68058. __extends(CircleOfConfusionPostProcess, _super);
  68059. /**
  68060. * Creates a new instance of @see CircleOfConfusionPostProcess
  68061. * @param name The name of the effect.
  68062. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  68063. * @param options The required width/height ratio to downsize to before computing the render pass.
  68064. * @param camera The camera to apply the render pass to.
  68065. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68066. * @param engine The engine which the post process will be applied. (default: current engine)
  68067. * @param reusable If the post process can be reused on the same frame. (default: false)
  68068. * @param textureType Type of textures used when performing the post process. (default: 0)
  68069. */
  68070. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType) {
  68071. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68072. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  68073. /**
  68074. * 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.
  68075. */
  68076. _this.lensSize = 50;
  68077. /**
  68078. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  68079. */
  68080. _this.fStop = 1.4;
  68081. /**
  68082. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  68083. */
  68084. _this.focusDistance = 2000;
  68085. /**
  68086. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  68087. */
  68088. _this.focalLength = 50;
  68089. _this.onApplyObservable.add(function (effect) {
  68090. effect.setTexture("depthSampler", depthTexture);
  68091. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  68092. var aperture = _this.lensSize / _this.fStop;
  68093. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  68094. effect.setFloat('focusDistance', _this.focusDistance);
  68095. effect.setFloat('cocPrecalculation', cocPrecalculation);
  68096. effect.setFloat2('cameraMinMaxZ', depthTexture.activeCamera.minZ, depthTexture.activeCamera.maxZ);
  68097. });
  68098. return _this;
  68099. }
  68100. return CircleOfConfusionPostProcess;
  68101. }(BABYLON.PostProcess));
  68102. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  68103. })(BABYLON || (BABYLON = {}));
  68104. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  68105. var BABYLON;
  68106. (function (BABYLON) {
  68107. /**
  68108. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  68109. */
  68110. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  68111. __extends(DepthOfFieldMergePostProcess, _super);
  68112. /**
  68113. * Creates a new instance of @see CircleOfConfusionPostProcess
  68114. * @param name The name of the effect.
  68115. * @param original The non-blurred image to be modified
  68116. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  68117. * @param blurSteps Incrimental bluring post processes.
  68118. * @param options The required width/height ratio to downsize to before computing the render pass.
  68119. * @param camera The camera to apply the render pass to.
  68120. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68121. * @param engine The engine which the post process will be applied. (default: current engine)
  68122. * @param reusable If the post process can be reused on the same frame. (default: false)
  68123. * @param textureType Type of textures used when performing the post process. (default: 0)
  68124. */
  68125. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType) {
  68126. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68127. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, "#define BLUR_LEVEL " + blurSteps.length + "\n", textureType) || this;
  68128. _this.onApplyObservable.add(function (effect) {
  68129. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  68130. effect.setTextureFromPostProcess("originalSampler", original);
  68131. blurSteps.forEach(function (step, index) {
  68132. effect.setTextureFromPostProcess("blurStep" + (index + 1), step);
  68133. });
  68134. });
  68135. return _this;
  68136. }
  68137. return DepthOfFieldMergePostProcess;
  68138. }(BABYLON.PostProcess));
  68139. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  68140. })(BABYLON || (BABYLON = {}));
  68141. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  68142. var BABYLON;
  68143. (function (BABYLON) {
  68144. /**
  68145. * Specifies the level of max blur that should be applied when using the depth of field effect
  68146. */
  68147. var DepthOfFieldEffectBlurLevel;
  68148. (function (DepthOfFieldEffectBlurLevel) {
  68149. /**
  68150. * Subtle blur
  68151. */
  68152. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  68153. /**
  68154. * Medium blur
  68155. */
  68156. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  68157. /**
  68158. * Large blur
  68159. */
  68160. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  68161. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  68162. ;
  68163. /**
  68164. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  68165. */
  68166. var DepthOfFieldEffect = /** @class */ (function (_super) {
  68167. __extends(DepthOfFieldEffect, _super);
  68168. /**
  68169. * Creates a new instance of @see DepthOfFieldEffect
  68170. * @param scene The scene the effect belongs to.
  68171. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  68172. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  68173. */
  68174. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType) {
  68175. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  68176. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  68177. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  68178. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  68179. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  68180. // Capture circle of confusion texture
  68181. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  68182. _this._depthOfFieldPass.autoClear = false;
  68183. // 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)
  68184. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  68185. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  68186. _this._depthOfFieldBlurY = [];
  68187. _this._depthOfFieldBlurX = [];
  68188. var blurCount = 1;
  68189. var kernelSize = 15;
  68190. switch (blurLevel) {
  68191. case DepthOfFieldEffectBlurLevel.High: {
  68192. blurCount = 3;
  68193. kernelSize = 51;
  68194. break;
  68195. }
  68196. case DepthOfFieldEffectBlurLevel.Medium: {
  68197. blurCount = 2;
  68198. kernelSize = 31;
  68199. break;
  68200. }
  68201. default: {
  68202. kernelSize = 15;
  68203. blurCount = 1;
  68204. break;
  68205. }
  68206. }
  68207. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  68208. for (var i = 0; i < blurCount; i++) {
  68209. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  68210. blurY.autoClear = false;
  68211. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  68212. blurX.autoClear = false;
  68213. _this._depthOfFieldBlurY.push(blurY);
  68214. _this._depthOfFieldBlurX.push(blurX);
  68215. }
  68216. // Merge blurred images with original image based on circleOfConfusion
  68217. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY.slice(1), 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  68218. _this._depthOfFieldMerge.autoClear = false;
  68219. // Set all post processes on the effect.
  68220. var effects = [_this._circleOfConfusion, _this._depthOfFieldPass];
  68221. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  68222. effects.push(_this._depthOfFieldBlurY[i]);
  68223. effects.push(_this._depthOfFieldBlurX[i]);
  68224. }
  68225. effects.push(_this._depthOfFieldMerge);
  68226. return effects;
  68227. }, true) || this;
  68228. return _this;
  68229. }
  68230. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  68231. get: function () {
  68232. return this._circleOfConfusion.focalLength;
  68233. },
  68234. /**
  68235. * The focal the length of the camera used in the effect
  68236. */
  68237. set: function (value) {
  68238. this._circleOfConfusion.focalLength = value;
  68239. },
  68240. enumerable: true,
  68241. configurable: true
  68242. });
  68243. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  68244. get: function () {
  68245. return this._circleOfConfusion.fStop;
  68246. },
  68247. /**
  68248. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  68249. */
  68250. set: function (value) {
  68251. this._circleOfConfusion.fStop = value;
  68252. },
  68253. enumerable: true,
  68254. configurable: true
  68255. });
  68256. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  68257. get: function () {
  68258. return this._circleOfConfusion.focusDistance;
  68259. },
  68260. /**
  68261. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  68262. */
  68263. set: function (value) {
  68264. this._circleOfConfusion.focusDistance = value;
  68265. },
  68266. enumerable: true,
  68267. configurable: true
  68268. });
  68269. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  68270. get: function () {
  68271. return this._circleOfConfusion.lensSize;
  68272. },
  68273. /**
  68274. * 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.
  68275. */
  68276. set: function (value) {
  68277. this._circleOfConfusion.lensSize = value;
  68278. },
  68279. enumerable: true,
  68280. configurable: true
  68281. });
  68282. /**
  68283. * Disposes each of the internal effects for a given camera.
  68284. * @param camera The camera to dispose the effect on.
  68285. */
  68286. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  68287. this._depthOfFieldPass.dispose(camera);
  68288. this._circleOfConfusion.dispose(camera);
  68289. this._depthOfFieldBlurX.forEach(function (element) {
  68290. element.dispose(camera);
  68291. });
  68292. this._depthOfFieldBlurY.forEach(function (element) {
  68293. element.dispose(camera);
  68294. });
  68295. this._depthOfFieldMerge.dispose(camera);
  68296. };
  68297. return DepthOfFieldEffect;
  68298. }(BABYLON.PostProcessRenderEffect));
  68299. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  68300. })(BABYLON || (BABYLON = {}));
  68301. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  68302. var BABYLON;
  68303. (function (BABYLON) {
  68304. /**
  68305. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  68306. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  68307. */
  68308. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  68309. __extends(DefaultRenderingPipeline, _super);
  68310. /**
  68311. * @constructor
  68312. * @param {string} name - The rendering pipeline name
  68313. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68314. * @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)
  68315. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68316. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  68317. */
  68318. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  68319. if (automaticBuild === void 0) { automaticBuild = true; }
  68320. var _this = _super.call(this, scene.getEngine(), name) || this;
  68321. /**
  68322. * ID of the pass post process used for bloom,
  68323. */
  68324. _this.PassPostProcessId = "PassPostProcessEffect";
  68325. /**
  68326. * ID of the highlight post process used for bloom,
  68327. */
  68328. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  68329. /**
  68330. * ID of the blurX post process used for bloom,
  68331. */
  68332. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  68333. /**
  68334. * ID of the blurY post process used for bloom,
  68335. */
  68336. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  68337. /**
  68338. * ID of the copy back post process used for bloom,
  68339. */
  68340. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  68341. /**
  68342. * ID of the image processing post process;
  68343. */
  68344. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  68345. /**
  68346. * ID of the Fast Approximate Anti-Aliasing post process;
  68347. */
  68348. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  68349. /**
  68350. * ID of the final merge post process;
  68351. */
  68352. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  68353. /**
  68354. * Animations which can be used to tweak settings over a period of time
  68355. */
  68356. _this.animations = [];
  68357. // Values
  68358. _this._bloomEnabled = false;
  68359. _this._depthOfFieldEnabled = false;
  68360. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  68361. _this._fxaaEnabled = false;
  68362. _this._imageProcessingEnabled = true;
  68363. _this._bloomScale = 0.6;
  68364. _this._buildAllowed = true;
  68365. /**
  68366. * Specifies the size of the bloom blur kernel, relative to the final output size
  68367. */
  68368. _this.bloomKernel = 64;
  68369. /**
  68370. * Specifies the weight of the bloom in the final rendering
  68371. */
  68372. _this._bloomWeight = 0.15;
  68373. _this._cameras = cameras || [];
  68374. _this._buildAllowed = automaticBuild;
  68375. // Initialize
  68376. _this._scene = scene;
  68377. var caps = _this._scene.getEngine().getCaps();
  68378. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  68379. // Misc
  68380. if (_this._hdr) {
  68381. if (caps.textureHalfFloatRender) {
  68382. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68383. }
  68384. else if (caps.textureFloatRender) {
  68385. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68386. }
  68387. }
  68388. else {
  68389. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68390. }
  68391. // Attach
  68392. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68393. _this._buildPipeline();
  68394. return _this;
  68395. }
  68396. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  68397. get: function () {
  68398. return this._bloomWeight;
  68399. },
  68400. /**
  68401. * The strength of the bloom.
  68402. */
  68403. set: function (value) {
  68404. if (this._bloomWeight === value) {
  68405. return;
  68406. }
  68407. this._bloomWeight = value;
  68408. if (this._hdr && this.copyBack) {
  68409. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  68410. }
  68411. },
  68412. enumerable: true,
  68413. configurable: true
  68414. });
  68415. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  68416. get: function () {
  68417. return this._bloomScale;
  68418. },
  68419. /**
  68420. * The scale of the bloom, lower value will provide better performance.
  68421. */
  68422. set: function (value) {
  68423. if (this._bloomScale === value) {
  68424. return;
  68425. }
  68426. this._bloomScale = value;
  68427. this._buildPipeline();
  68428. },
  68429. enumerable: true,
  68430. configurable: true
  68431. });
  68432. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  68433. get: function () {
  68434. return this._bloomEnabled;
  68435. },
  68436. /**
  68437. * Enable or disable the bloom from the pipeline
  68438. */
  68439. set: function (enabled) {
  68440. if (this._bloomEnabled === enabled) {
  68441. return;
  68442. }
  68443. this._bloomEnabled = enabled;
  68444. this._buildPipeline();
  68445. },
  68446. enumerable: true,
  68447. configurable: true
  68448. });
  68449. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  68450. /**
  68451. * If the depth of field is enabled.
  68452. */
  68453. get: function () {
  68454. return this._depthOfFieldEnabled;
  68455. },
  68456. set: function (enabled) {
  68457. if (this._depthOfFieldEnabled === enabled) {
  68458. return;
  68459. }
  68460. this._depthOfFieldEnabled = enabled;
  68461. this._buildPipeline();
  68462. },
  68463. enumerable: true,
  68464. configurable: true
  68465. });
  68466. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  68467. /**
  68468. * Blur level of the depth of field effect. (Higher blur will effect performance)
  68469. */
  68470. get: function () {
  68471. return this._depthOfFieldBlurLevel;
  68472. },
  68473. set: function (value) {
  68474. if (this._depthOfFieldBlurLevel === value) {
  68475. return;
  68476. }
  68477. this._depthOfFieldBlurLevel = value;
  68478. this._buildPipeline();
  68479. },
  68480. enumerable: true,
  68481. configurable: true
  68482. });
  68483. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  68484. get: function () {
  68485. return this._fxaaEnabled;
  68486. },
  68487. /**
  68488. * If the anti aliasing is enabled.
  68489. */
  68490. set: function (enabled) {
  68491. if (this._fxaaEnabled === enabled) {
  68492. return;
  68493. }
  68494. this._fxaaEnabled = enabled;
  68495. this._buildPipeline();
  68496. },
  68497. enumerable: true,
  68498. configurable: true
  68499. });
  68500. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  68501. get: function () {
  68502. return this._imageProcessingEnabled;
  68503. },
  68504. /**
  68505. * If image processing is enabled.
  68506. */
  68507. set: function (enabled) {
  68508. if (this._imageProcessingEnabled === enabled) {
  68509. return;
  68510. }
  68511. this._imageProcessingEnabled = enabled;
  68512. this._buildPipeline();
  68513. },
  68514. enumerable: true,
  68515. configurable: true
  68516. });
  68517. /**
  68518. * Force the compilation of the entire pipeline.
  68519. */
  68520. DefaultRenderingPipeline.prototype.prepare = function () {
  68521. var previousState = this._buildAllowed;
  68522. this._buildAllowed = true;
  68523. this._buildPipeline();
  68524. this._buildAllowed = previousState;
  68525. };
  68526. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  68527. var _this = this;
  68528. if (!this._buildAllowed) {
  68529. return;
  68530. }
  68531. var engine = this._scene.getEngine();
  68532. this._disposePostProcesses();
  68533. this._reset();
  68534. if (this.depthOfFieldEnabled) {
  68535. // Enable and get current depth map
  68536. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  68537. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, depthTexture, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  68538. this.addEffect(this.depthOfField);
  68539. }
  68540. if (this.bloomEnabled) {
  68541. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68542. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  68543. if (!this._hdr) {
  68544. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68545. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  68546. this.highlights.autoClear = false;
  68547. this.highlights.alwaysForcePOT = true;
  68548. }
  68549. this.blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68550. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  68551. this.blurX.alwaysForcePOT = true;
  68552. this.blurX.autoClear = false;
  68553. this.blurX.onActivateObservable.add(function () {
  68554. var dw = _this.blurX.width / engine.getRenderWidth(true);
  68555. _this.blurX.kernel = _this.bloomKernel * dw;
  68556. });
  68557. this.blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68558. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  68559. this.blurY.alwaysForcePOT = true;
  68560. this.blurY.autoClear = false;
  68561. this.blurY.onActivateObservable.add(function () {
  68562. var dh = _this.blurY.height / engine.getRenderHeight(true);
  68563. _this.blurY.kernel = _this.bloomKernel * dh;
  68564. });
  68565. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68566. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  68567. this.copyBack.alwaysForcePOT = true;
  68568. if (this._hdr) {
  68569. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  68570. var w = this.bloomWeight;
  68571. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  68572. }
  68573. else {
  68574. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  68575. }
  68576. this.copyBack.autoClear = false;
  68577. }
  68578. if (this._imageProcessingEnabled) {
  68579. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68580. if (this._hdr) {
  68581. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  68582. }
  68583. else {
  68584. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  68585. }
  68586. }
  68587. if (this.fxaaEnabled) {
  68588. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68589. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  68590. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  68591. }
  68592. else if (this._hdr && this.imageProcessing) {
  68593. this.finalMerge = this.imageProcessing;
  68594. }
  68595. else {
  68596. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68597. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  68598. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  68599. }
  68600. if (this.bloomEnabled) {
  68601. if (this._hdr) {
  68602. this.copyBack.shareOutputWith(this.blurX);
  68603. if (this.imageProcessing) {
  68604. this.imageProcessing.shareOutputWith(this.pass);
  68605. this.imageProcessing.autoClear = false;
  68606. }
  68607. else if (this.fxaa) {
  68608. this.fxaa.shareOutputWith(this.pass);
  68609. }
  68610. else {
  68611. this.finalMerge.shareOutputWith(this.pass);
  68612. }
  68613. }
  68614. else {
  68615. if (this.fxaa) {
  68616. this.fxaa.shareOutputWith(this.pass);
  68617. }
  68618. else {
  68619. this.finalMerge.shareOutputWith(this.pass);
  68620. }
  68621. }
  68622. }
  68623. if (this._cameras !== null) {
  68624. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  68625. }
  68626. this._enableMSAAOnFirstPostProcess();
  68627. };
  68628. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  68629. for (var i = 0; i < this._cameras.length; i++) {
  68630. var camera = this._cameras[i];
  68631. if (this.pass) {
  68632. this.pass.dispose(camera);
  68633. }
  68634. if (this.highlights) {
  68635. this.highlights.dispose(camera);
  68636. }
  68637. if (this.blurX) {
  68638. this.blurX.dispose(camera);
  68639. }
  68640. if (this.blurY) {
  68641. this.blurY.dispose(camera);
  68642. }
  68643. if (this.copyBack) {
  68644. this.copyBack.dispose(camera);
  68645. }
  68646. if (this.imageProcessing) {
  68647. this.imageProcessing.dispose(camera);
  68648. }
  68649. if (this.fxaa) {
  68650. this.fxaa.dispose(camera);
  68651. }
  68652. if (this.finalMerge) {
  68653. this.finalMerge.dispose(camera);
  68654. }
  68655. if (this.depthOfField) {
  68656. this.depthOfField.disposeEffects(camera);
  68657. }
  68658. }
  68659. this.pass = null;
  68660. this.highlights = null;
  68661. this.blurX = null;
  68662. this.blurY = null;
  68663. this.copyBack = null;
  68664. this.imageProcessing = null;
  68665. this.fxaa = null;
  68666. this.finalMerge = null;
  68667. this.depthOfField = null;
  68668. };
  68669. /**
  68670. * Dispose of the pipeline and stop all post processes
  68671. */
  68672. DefaultRenderingPipeline.prototype.dispose = function () {
  68673. this._disposePostProcesses();
  68674. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  68675. _super.prototype.dispose.call(this);
  68676. };
  68677. /**
  68678. * Serialize the rendering pipeline (Used when exporting)
  68679. * @returns the serialized object
  68680. */
  68681. DefaultRenderingPipeline.prototype.serialize = function () {
  68682. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  68683. serializationObject.customType = "DefaultRenderingPipeline";
  68684. return serializationObject;
  68685. };
  68686. /**
  68687. * Parse the serialized pipeline
  68688. * @param source Source pipeline.
  68689. * @param scene The scene to load the pipeline to.
  68690. * @param rootUrl The URL of the serialized pipeline.
  68691. * @returns An instantiated pipeline from the serialized object.
  68692. */
  68693. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  68694. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  68695. };
  68696. __decorate([
  68697. BABYLON.serialize()
  68698. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  68699. __decorate([
  68700. BABYLON.serialize()
  68701. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  68702. __decorate([
  68703. BABYLON.serialize()
  68704. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  68705. __decorate([
  68706. BABYLON.serialize()
  68707. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  68708. __decorate([
  68709. BABYLON.serialize()
  68710. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  68711. __decorate([
  68712. BABYLON.serialize()
  68713. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  68714. __decorate([
  68715. BABYLON.serialize()
  68716. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  68717. __decorate([
  68718. BABYLON.serialize()
  68719. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  68720. __decorate([
  68721. BABYLON.serialize()
  68722. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  68723. __decorate([
  68724. BABYLON.serialize()
  68725. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  68726. return DefaultRenderingPipeline;
  68727. }(BABYLON.PostProcessRenderPipeline));
  68728. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  68729. })(BABYLON || (BABYLON = {}));
  68730. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  68731. var BABYLON;
  68732. (function (BABYLON) {
  68733. /**
  68734. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  68735. */
  68736. var GeometryBufferRenderer = /** @class */ (function () {
  68737. /**
  68738. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  68739. * @param scene The scene the buffer belongs to
  68740. * @param ratio How big is the buffer related to the main canvas.
  68741. */
  68742. function GeometryBufferRenderer(scene, ratio) {
  68743. if (ratio === void 0) { ratio = 1; }
  68744. this._enablePosition = false;
  68745. this._scene = scene;
  68746. this._ratio = ratio;
  68747. // Render target
  68748. this._createRenderTargets();
  68749. }
  68750. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  68751. /**
  68752. * Set the render list (meshes to be rendered) used in the G buffer.
  68753. */
  68754. set: function (meshes) {
  68755. this._multiRenderTarget.renderList = meshes;
  68756. },
  68757. enumerable: true,
  68758. configurable: true
  68759. });
  68760. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  68761. /**
  68762. * Gets wether or not G buffer are supported by the running hardware.
  68763. * This requires draw buffer supports
  68764. */
  68765. get: function () {
  68766. return this._multiRenderTarget.isSupported;
  68767. },
  68768. enumerable: true,
  68769. configurable: true
  68770. });
  68771. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  68772. /**
  68773. * Gets wether or not position are enabled for the G buffer.
  68774. */
  68775. get: function () {
  68776. return this._enablePosition;
  68777. },
  68778. /**
  68779. * Sets wether or not position are enabled for the G buffer.
  68780. */
  68781. set: function (enable) {
  68782. this._enablePosition = enable;
  68783. this.dispose();
  68784. this._createRenderTargets();
  68785. },
  68786. enumerable: true,
  68787. configurable: true
  68788. });
  68789. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  68790. /**
  68791. * Gets the scene associated with the buffer.
  68792. */
  68793. get: function () {
  68794. return this._scene;
  68795. },
  68796. enumerable: true,
  68797. configurable: true
  68798. });
  68799. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  68800. /**
  68801. * Gets the ratio used by the buffer during its creation.
  68802. * How big is the buffer related to the main canvas.
  68803. */
  68804. get: function () {
  68805. return this._ratio;
  68806. },
  68807. enumerable: true,
  68808. configurable: true
  68809. });
  68810. /**
  68811. * Checks wether everything is ready to render a submesh to the G buffer.
  68812. * @param subMesh the submesh to check readiness for
  68813. * @param useInstances is the mesh drawn using instance or not
  68814. * @returns true if ready otherwise false
  68815. */
  68816. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  68817. var material = subMesh.getMaterial();
  68818. if (material && material.disableDepthWrite) {
  68819. return false;
  68820. }
  68821. var defines = [];
  68822. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  68823. var mesh = subMesh.getMesh();
  68824. // Alpha test
  68825. if (material && material.needAlphaTesting()) {
  68826. defines.push("#define ALPHATEST");
  68827. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68828. attribs.push(BABYLON.VertexBuffer.UVKind);
  68829. defines.push("#define UV1");
  68830. }
  68831. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68832. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68833. defines.push("#define UV2");
  68834. }
  68835. }
  68836. // Buffers
  68837. if (this._enablePosition) {
  68838. defines.push("#define POSITION");
  68839. }
  68840. // Bones
  68841. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68842. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68843. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68844. if (mesh.numBoneInfluencers > 4) {
  68845. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  68846. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  68847. }
  68848. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68849. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  68850. }
  68851. else {
  68852. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68853. }
  68854. // Instances
  68855. if (useInstances) {
  68856. defines.push("#define INSTANCES");
  68857. attribs.push("world0");
  68858. attribs.push("world1");
  68859. attribs.push("world2");
  68860. attribs.push("world3");
  68861. }
  68862. // Get correct effect
  68863. var join = defines.join("\n");
  68864. if (this._cachedDefines !== join) {
  68865. this._cachedDefines = join;
  68866. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  68867. }
  68868. return this._effect.isReady();
  68869. };
  68870. /**
  68871. * Gets the current underlying G Buffer.
  68872. * @returns the buffer
  68873. */
  68874. GeometryBufferRenderer.prototype.getGBuffer = function () {
  68875. return this._multiRenderTarget;
  68876. };
  68877. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  68878. /**
  68879. * Gets the number of samples used to render the buffer (anti aliasing).
  68880. */
  68881. get: function () {
  68882. return this._multiRenderTarget.samples;
  68883. },
  68884. /**
  68885. * Sets the number of samples used to render the buffer (anti aliasing).
  68886. */
  68887. set: function (value) {
  68888. this._multiRenderTarget.samples = value;
  68889. },
  68890. enumerable: true,
  68891. configurable: true
  68892. });
  68893. /**
  68894. * Disposes the renderer and frees up associated resources.
  68895. */
  68896. GeometryBufferRenderer.prototype.dispose = function () {
  68897. this.getGBuffer().dispose();
  68898. };
  68899. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  68900. var _this = this;
  68901. var engine = this._scene.getEngine();
  68902. var count = this._enablePosition ? 3 : 2;
  68903. 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 });
  68904. if (!this.isSupported) {
  68905. return;
  68906. }
  68907. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68908. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68909. this._multiRenderTarget.refreshRate = 1;
  68910. this._multiRenderTarget.renderParticles = false;
  68911. this._multiRenderTarget.renderList = null;
  68912. // set default depth value to 1.0 (far away)
  68913. this._multiRenderTarget.onClearObservable.add(function (engine) {
  68914. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  68915. });
  68916. // Custom render function
  68917. var renderSubMesh = function (subMesh) {
  68918. var mesh = subMesh.getRenderingMesh();
  68919. var scene = _this._scene;
  68920. var engine = scene.getEngine();
  68921. var material = subMesh.getMaterial();
  68922. if (!material) {
  68923. return;
  68924. }
  68925. // Culling
  68926. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  68927. // Managing instances
  68928. var batch = mesh._getInstancesRenderList(subMesh._id);
  68929. if (batch.mustReturn) {
  68930. return;
  68931. }
  68932. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  68933. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  68934. engine.enableEffect(_this._effect);
  68935. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  68936. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  68937. _this._effect.setMatrix("view", scene.getViewMatrix());
  68938. // Alpha test
  68939. if (material && material.needAlphaTesting()) {
  68940. var alphaTexture = material.getAlphaTestTexture();
  68941. if (alphaTexture) {
  68942. _this._effect.setTexture("diffuseSampler", alphaTexture);
  68943. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  68944. }
  68945. }
  68946. // Bones
  68947. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  68948. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  68949. }
  68950. // Draw
  68951. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  68952. }
  68953. };
  68954. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  68955. var index;
  68956. if (depthOnlySubMeshes.length) {
  68957. engine.setColorWrite(false);
  68958. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  68959. renderSubMesh(depthOnlySubMeshes.data[index]);
  68960. }
  68961. engine.setColorWrite(true);
  68962. }
  68963. for (index = 0; index < opaqueSubMeshes.length; index++) {
  68964. renderSubMesh(opaqueSubMeshes.data[index]);
  68965. }
  68966. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  68967. renderSubMesh(alphaTestSubMeshes.data[index]);
  68968. }
  68969. };
  68970. };
  68971. return GeometryBufferRenderer;
  68972. }());
  68973. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  68974. })(BABYLON || (BABYLON = {}));
  68975. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  68976. var BABYLON;
  68977. (function (BABYLON) {
  68978. var RefractionPostProcess = /** @class */ (function (_super) {
  68979. __extends(RefractionPostProcess, _super);
  68980. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  68981. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  68982. _this.color = color;
  68983. _this.depth = depth;
  68984. _this.colorLevel = colorLevel;
  68985. _this._ownRefractionTexture = true;
  68986. _this.onActivateObservable.add(function (cam) {
  68987. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  68988. });
  68989. _this.onApplyObservable.add(function (effect) {
  68990. effect.setColor3("baseColor", _this.color);
  68991. effect.setFloat("depth", _this.depth);
  68992. effect.setFloat("colorLevel", _this.colorLevel);
  68993. effect.setTexture("refractionSampler", _this._refTexture);
  68994. });
  68995. return _this;
  68996. }
  68997. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  68998. /**
  68999. * Gets or sets the refraction texture
  69000. * Please note that you are responsible for disposing the texture if you set it manually
  69001. */
  69002. get: function () {
  69003. return this._refTexture;
  69004. },
  69005. set: function (value) {
  69006. if (this._refTexture && this._ownRefractionTexture) {
  69007. this._refTexture.dispose();
  69008. }
  69009. this._refTexture = value;
  69010. this._ownRefractionTexture = false;
  69011. },
  69012. enumerable: true,
  69013. configurable: true
  69014. });
  69015. // Methods
  69016. RefractionPostProcess.prototype.dispose = function (camera) {
  69017. if (this._refTexture && this._ownRefractionTexture) {
  69018. this._refTexture.dispose();
  69019. this._refTexture = null;
  69020. }
  69021. _super.prototype.dispose.call(this, camera);
  69022. };
  69023. return RefractionPostProcess;
  69024. }(BABYLON.PostProcess));
  69025. BABYLON.RefractionPostProcess = RefractionPostProcess;
  69026. })(BABYLON || (BABYLON = {}));
  69027. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  69028. var BABYLON;
  69029. (function (BABYLON) {
  69030. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  69031. __extends(BlackAndWhitePostProcess, _super);
  69032. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  69033. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  69034. _this.degree = 1;
  69035. _this.onApplyObservable.add(function (effect) {
  69036. effect.setFloat("degree", _this.degree);
  69037. });
  69038. return _this;
  69039. }
  69040. return BlackAndWhitePostProcess;
  69041. }(BABYLON.PostProcess));
  69042. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  69043. })(BABYLON || (BABYLON = {}));
  69044. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  69045. var BABYLON;
  69046. (function (BABYLON) {
  69047. var ConvolutionPostProcess = /** @class */ (function (_super) {
  69048. __extends(ConvolutionPostProcess, _super);
  69049. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  69050. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  69051. _this.kernel = kernel;
  69052. _this.onApply = function (effect) {
  69053. effect.setFloat2("screenSize", _this.width, _this.height);
  69054. effect.setArray("kernel", _this.kernel);
  69055. };
  69056. return _this;
  69057. }
  69058. // Statics
  69059. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  69060. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  69061. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  69062. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  69063. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  69064. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  69065. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  69066. return ConvolutionPostProcess;
  69067. }(BABYLON.PostProcess));
  69068. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  69069. })(BABYLON || (BABYLON = {}));
  69070. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  69071. var BABYLON;
  69072. (function (BABYLON) {
  69073. var FilterPostProcess = /** @class */ (function (_super) {
  69074. __extends(FilterPostProcess, _super);
  69075. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  69076. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  69077. _this.kernelMatrix = kernelMatrix;
  69078. _this.onApply = function (effect) {
  69079. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  69080. };
  69081. return _this;
  69082. }
  69083. return FilterPostProcess;
  69084. }(BABYLON.PostProcess));
  69085. BABYLON.FilterPostProcess = FilterPostProcess;
  69086. })(BABYLON || (BABYLON = {}));
  69087. //# sourceMappingURL=babylon.filterPostProcess.js.map
  69088. var BABYLON;
  69089. (function (BABYLON) {
  69090. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  69091. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  69092. __extends(VolumetricLightScatteringPostProcess, _super);
  69093. /**
  69094. * @constructor
  69095. * @param {string} name - The post-process name
  69096. * @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)
  69097. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  69098. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  69099. * @param {number} samples - The post-process quality, default 100
  69100. * @param {number} samplingMode - The post-process filtering mode
  69101. * @param {BABYLON.Engine} engine - The babylon engine
  69102. * @param {boolean} reusable - If the post-process is reusable
  69103. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  69104. */
  69105. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  69106. if (samples === void 0) { samples = 100; }
  69107. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69108. 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;
  69109. _this._screenCoordinates = BABYLON.Vector2.Zero();
  69110. /**
  69111. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  69112. * @type {Vector3}
  69113. */
  69114. _this.customMeshPosition = BABYLON.Vector3.Zero();
  69115. /**
  69116. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  69117. * @type {boolean}
  69118. */
  69119. _this.useCustomMeshPosition = false;
  69120. /**
  69121. * If the post-process should inverse the light scattering direction
  69122. * @type {boolean}
  69123. */
  69124. _this.invert = true;
  69125. /**
  69126. * Array containing the excluded meshes not rendered in the internal pass
  69127. */
  69128. _this.excludedMeshes = new Array();
  69129. /**
  69130. * Controls the overall intensity of the post-process
  69131. * @type {number}
  69132. */
  69133. _this.exposure = 0.3;
  69134. /**
  69135. * Dissipates each sample's contribution in range [0, 1]
  69136. * @type {number}
  69137. */
  69138. _this.decay = 0.96815;
  69139. /**
  69140. * Controls the overall intensity of each sample
  69141. * @type {number}
  69142. */
  69143. _this.weight = 0.58767;
  69144. /**
  69145. * Controls the density of each sample
  69146. * @type {number}
  69147. */
  69148. _this.density = 0.926;
  69149. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  69150. engine = scene.getEngine();
  69151. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  69152. // Configure mesh
  69153. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  69154. // Configure
  69155. _this._createPass(scene, ratio.passRatio || ratio);
  69156. _this.onActivate = function (camera) {
  69157. if (!_this.isSupported) {
  69158. _this.dispose(camera);
  69159. }
  69160. _this.onActivate = null;
  69161. };
  69162. _this.onApplyObservable.add(function (effect) {
  69163. _this._updateMeshScreenCoordinates(scene);
  69164. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  69165. effect.setFloat("exposure", _this.exposure);
  69166. effect.setFloat("decay", _this.decay);
  69167. effect.setFloat("weight", _this.weight);
  69168. effect.setFloat("density", _this.density);
  69169. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  69170. });
  69171. return _this;
  69172. }
  69173. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  69174. get: function () {
  69175. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  69176. return false;
  69177. },
  69178. set: function (useDiffuseColor) {
  69179. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  69180. },
  69181. enumerable: true,
  69182. configurable: true
  69183. });
  69184. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  69185. return "VolumetricLightScatteringPostProcess";
  69186. };
  69187. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  69188. var mesh = subMesh.getMesh();
  69189. // Render this.mesh as default
  69190. if (mesh === this.mesh && mesh.material) {
  69191. return mesh.material.isReady(mesh);
  69192. }
  69193. var defines = [];
  69194. var attribs = [BABYLON.VertexBuffer.PositionKind];
  69195. var material = subMesh.getMaterial();
  69196. // Alpha test
  69197. if (material) {
  69198. if (material.needAlphaTesting()) {
  69199. defines.push("#define ALPHATEST");
  69200. }
  69201. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  69202. attribs.push(BABYLON.VertexBuffer.UVKind);
  69203. defines.push("#define UV1");
  69204. }
  69205. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  69206. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  69207. defines.push("#define UV2");
  69208. }
  69209. }
  69210. // Bones
  69211. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69212. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  69213. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  69214. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  69215. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  69216. }
  69217. else {
  69218. defines.push("#define NUM_BONE_INFLUENCERS 0");
  69219. }
  69220. // Instances
  69221. if (useInstances) {
  69222. defines.push("#define INSTANCES");
  69223. attribs.push("world0");
  69224. attribs.push("world1");
  69225. attribs.push("world2");
  69226. attribs.push("world3");
  69227. }
  69228. // Get correct effect
  69229. var join = defines.join("\n");
  69230. if (this._cachedDefines !== join) {
  69231. this._cachedDefines = join;
  69232. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  69233. }
  69234. return this._volumetricLightScatteringPass.isReady();
  69235. };
  69236. /**
  69237. * Sets the new light position for light scattering effect
  69238. * @param {BABYLON.Vector3} The new custom light position
  69239. */
  69240. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  69241. this.customMeshPosition = position;
  69242. };
  69243. /**
  69244. * Returns the light position for light scattering effect
  69245. * @return {BABYLON.Vector3} The custom light position
  69246. */
  69247. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  69248. return this.customMeshPosition;
  69249. };
  69250. /**
  69251. * Disposes the internal assets and detaches the post-process from the camera
  69252. */
  69253. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  69254. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  69255. if (rttIndex !== -1) {
  69256. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  69257. }
  69258. this._volumetricLightScatteringRTT.dispose();
  69259. _super.prototype.dispose.call(this, camera);
  69260. };
  69261. /**
  69262. * Returns the render target texture used by the post-process
  69263. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  69264. */
  69265. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  69266. return this._volumetricLightScatteringRTT;
  69267. };
  69268. // Private methods
  69269. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  69270. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  69271. return true;
  69272. }
  69273. return false;
  69274. };
  69275. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  69276. var _this = this;
  69277. var engine = scene.getEngine();
  69278. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  69279. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69280. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69281. this._volumetricLightScatteringRTT.renderList = null;
  69282. this._volumetricLightScatteringRTT.renderParticles = false;
  69283. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  69284. var camera = this.getCamera();
  69285. if (camera) {
  69286. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  69287. }
  69288. else {
  69289. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  69290. }
  69291. // Custom render function for submeshes
  69292. var renderSubMesh = function (subMesh) {
  69293. var mesh = subMesh.getRenderingMesh();
  69294. if (_this._meshExcluded(mesh)) {
  69295. return;
  69296. }
  69297. var material = subMesh.getMaterial();
  69298. if (!material) {
  69299. return;
  69300. }
  69301. var scene = mesh.getScene();
  69302. var engine = scene.getEngine();
  69303. // Culling
  69304. engine.setState(material.backFaceCulling);
  69305. // Managing instances
  69306. var batch = mesh._getInstancesRenderList(subMesh._id);
  69307. if (batch.mustReturn) {
  69308. return;
  69309. }
  69310. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  69311. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  69312. var effect = _this._volumetricLightScatteringPass;
  69313. if (mesh === _this.mesh) {
  69314. if (subMesh.effect) {
  69315. effect = subMesh.effect;
  69316. }
  69317. else {
  69318. effect = material.getEffect();
  69319. }
  69320. }
  69321. engine.enableEffect(effect);
  69322. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  69323. if (mesh === _this.mesh) {
  69324. material.bind(mesh.getWorldMatrix(), mesh);
  69325. }
  69326. else {
  69327. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  69328. // Alpha test
  69329. if (material && material.needAlphaTesting()) {
  69330. var alphaTexture = material.getAlphaTestTexture();
  69331. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  69332. if (alphaTexture) {
  69333. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  69334. }
  69335. }
  69336. // Bones
  69337. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  69338. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  69339. }
  69340. }
  69341. // Draw
  69342. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  69343. }
  69344. };
  69345. // Render target texture callbacks
  69346. var savedSceneClearColor;
  69347. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  69348. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  69349. savedSceneClearColor = scene.clearColor;
  69350. scene.clearColor = sceneClearColor;
  69351. });
  69352. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  69353. scene.clearColor = savedSceneClearColor;
  69354. });
  69355. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  69356. var engine = scene.getEngine();
  69357. var index;
  69358. if (depthOnlySubMeshes.length) {
  69359. engine.setColorWrite(false);
  69360. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  69361. renderSubMesh(depthOnlySubMeshes.data[index]);
  69362. }
  69363. engine.setColorWrite(true);
  69364. }
  69365. for (index = 0; index < opaqueSubMeshes.length; index++) {
  69366. renderSubMesh(opaqueSubMeshes.data[index]);
  69367. }
  69368. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  69369. renderSubMesh(alphaTestSubMeshes.data[index]);
  69370. }
  69371. if (transparentSubMeshes.length) {
  69372. // Sort sub meshes
  69373. for (index = 0; index < transparentSubMeshes.length; index++) {
  69374. var submesh = transparentSubMeshes.data[index];
  69375. var boundingInfo = submesh.getBoundingInfo();
  69376. if (boundingInfo && scene.activeCamera) {
  69377. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  69378. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  69379. }
  69380. }
  69381. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  69382. sortedArray.sort(function (a, b) {
  69383. // Alpha index first
  69384. if (a._alphaIndex > b._alphaIndex) {
  69385. return 1;
  69386. }
  69387. if (a._alphaIndex < b._alphaIndex) {
  69388. return -1;
  69389. }
  69390. // Then distance to camera
  69391. if (a._distanceToCamera < b._distanceToCamera) {
  69392. return 1;
  69393. }
  69394. if (a._distanceToCamera > b._distanceToCamera) {
  69395. return -1;
  69396. }
  69397. return 0;
  69398. });
  69399. // Render sub meshes
  69400. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  69401. for (index = 0; index < sortedArray.length; index++) {
  69402. renderSubMesh(sortedArray[index]);
  69403. }
  69404. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  69405. }
  69406. };
  69407. };
  69408. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  69409. var transform = scene.getTransformMatrix();
  69410. var meshPosition;
  69411. if (this.useCustomMeshPosition) {
  69412. meshPosition = this.customMeshPosition;
  69413. }
  69414. else if (this.attachedNode) {
  69415. meshPosition = this.attachedNode.position;
  69416. }
  69417. else {
  69418. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  69419. }
  69420. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  69421. this._screenCoordinates.x = pos.x / this._viewPort.width;
  69422. this._screenCoordinates.y = pos.y / this._viewPort.height;
  69423. if (this.invert)
  69424. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  69425. };
  69426. // Static methods
  69427. /**
  69428. * Creates a default mesh for the Volumeric Light Scattering post-process
  69429. * @param {string} The mesh name
  69430. * @param {BABYLON.Scene} The scene where to create the mesh
  69431. * @return {BABYLON.Mesh} the default mesh
  69432. */
  69433. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  69434. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  69435. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  69436. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  69437. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  69438. mesh.material = material;
  69439. return mesh;
  69440. };
  69441. __decorate([
  69442. BABYLON.serializeAsVector3()
  69443. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  69444. __decorate([
  69445. BABYLON.serialize()
  69446. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  69447. __decorate([
  69448. BABYLON.serialize()
  69449. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  69450. __decorate([
  69451. BABYLON.serializeAsMeshReference()
  69452. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  69453. __decorate([
  69454. BABYLON.serialize()
  69455. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  69456. __decorate([
  69457. BABYLON.serialize()
  69458. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  69459. __decorate([
  69460. BABYLON.serialize()
  69461. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  69462. __decorate([
  69463. BABYLON.serialize()
  69464. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  69465. __decorate([
  69466. BABYLON.serialize()
  69467. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  69468. return VolumetricLightScatteringPostProcess;
  69469. }(BABYLON.PostProcess));
  69470. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  69471. })(BABYLON || (BABYLON = {}));
  69472. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  69473. //
  69474. // This post-process allows the modification of rendered colors by using
  69475. // a 'look-up table' (LUT). This effect is also called Color Grading.
  69476. //
  69477. // The object needs to be provided an url to a texture containing the color
  69478. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  69479. // Use an image editing software to tweak the LUT to match your needs.
  69480. //
  69481. // For an example of a color LUT, see here:
  69482. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  69483. // For explanations on color grading, see here:
  69484. // http://udn.epicgames.com/Three/ColorGrading.html
  69485. //
  69486. var BABYLON;
  69487. (function (BABYLON) {
  69488. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  69489. __extends(ColorCorrectionPostProcess, _super);
  69490. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  69491. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  69492. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  69493. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  69494. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69495. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69496. _this.onApply = function (effect) {
  69497. effect.setTexture("colorTable", _this._colorTableTexture);
  69498. };
  69499. return _this;
  69500. }
  69501. return ColorCorrectionPostProcess;
  69502. }(BABYLON.PostProcess));
  69503. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  69504. })(BABYLON || (BABYLON = {}));
  69505. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  69506. var BABYLON;
  69507. (function (BABYLON) {
  69508. var TonemappingOperator;
  69509. (function (TonemappingOperator) {
  69510. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  69511. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  69512. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  69513. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  69514. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  69515. ;
  69516. var TonemapPostProcess = /** @class */ (function (_super) {
  69517. __extends(TonemapPostProcess, _super);
  69518. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  69519. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69520. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69521. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  69522. _this._operator = _operator;
  69523. _this.exposureAdjustment = exposureAdjustment;
  69524. var defines = "#define ";
  69525. if (_this._operator === TonemappingOperator.Hable)
  69526. defines += "HABLE_TONEMAPPING";
  69527. else if (_this._operator === TonemappingOperator.Reinhard)
  69528. defines += "REINHARD_TONEMAPPING";
  69529. else if (_this._operator === TonemappingOperator.HejiDawson)
  69530. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  69531. else if (_this._operator === TonemappingOperator.Photographic)
  69532. defines += "PHOTOGRAPHIC_TONEMAPPING";
  69533. //sadly a second call to create the effect.
  69534. _this.updateEffect(defines);
  69535. _this.onApply = function (effect) {
  69536. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  69537. };
  69538. return _this;
  69539. }
  69540. return TonemapPostProcess;
  69541. }(BABYLON.PostProcess));
  69542. BABYLON.TonemapPostProcess = TonemapPostProcess;
  69543. })(BABYLON || (BABYLON = {}));
  69544. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  69545. var BABYLON;
  69546. (function (BABYLON) {
  69547. var DisplayPassPostProcess = /** @class */ (function (_super) {
  69548. __extends(DisplayPassPostProcess, _super);
  69549. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  69550. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  69551. }
  69552. return DisplayPassPostProcess;
  69553. }(BABYLON.PostProcess));
  69554. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  69555. })(BABYLON || (BABYLON = {}));
  69556. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  69557. var BABYLON;
  69558. (function (BABYLON) {
  69559. var HighlightsPostProcess = /** @class */ (function (_super) {
  69560. __extends(HighlightsPostProcess, _super);
  69561. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  69562. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69563. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  69564. }
  69565. return HighlightsPostProcess;
  69566. }(BABYLON.PostProcess));
  69567. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  69568. })(BABYLON || (BABYLON = {}));
  69569. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  69570. var BABYLON;
  69571. (function (BABYLON) {
  69572. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  69573. __extends(ImageProcessingPostProcess, _super);
  69574. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  69575. if (camera === void 0) { camera = null; }
  69576. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69577. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  69578. _this._fromLinearSpace = true;
  69579. /**
  69580. * Defines cache preventing GC.
  69581. */
  69582. _this._defines = {
  69583. IMAGEPROCESSING: false,
  69584. VIGNETTE: false,
  69585. VIGNETTEBLENDMODEMULTIPLY: false,
  69586. VIGNETTEBLENDMODEOPAQUE: false,
  69587. TONEMAPPING: false,
  69588. CONTRAST: false,
  69589. COLORCURVES: false,
  69590. COLORGRADING: false,
  69591. COLORGRADING3D: false,
  69592. FROMLINEARSPACE: false,
  69593. SAMPLER3DGREENDEPTH: false,
  69594. SAMPLER3DBGRMAP: false,
  69595. IMAGEPROCESSINGPOSTPROCESS: false,
  69596. EXPOSURE: false,
  69597. };
  69598. // Setup the configuration as forced by the constructor. This would then not force the
  69599. // scene materials output in linear space and let untouched the default forward pass.
  69600. if (imageProcessingConfiguration) {
  69601. imageProcessingConfiguration.applyByPostProcess = true;
  69602. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  69603. // This will cause the shader to be compiled
  69604. _this.fromLinearSpace = false;
  69605. }
  69606. else {
  69607. _this._attachImageProcessingConfiguration(null, true);
  69608. _this.imageProcessingConfiguration.applyByPostProcess = true;
  69609. }
  69610. _this.onApply = function (effect) {
  69611. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  69612. };
  69613. return _this;
  69614. }
  69615. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  69616. /**
  69617. * Gets the image processing configuration used either in this material.
  69618. */
  69619. get: function () {
  69620. return this._imageProcessingConfiguration;
  69621. },
  69622. /**
  69623. * Sets the Default image processing configuration used either in the this material.
  69624. *
  69625. * If sets to null, the scene one is in use.
  69626. */
  69627. set: function (value) {
  69628. this._attachImageProcessingConfiguration(value);
  69629. },
  69630. enumerable: true,
  69631. configurable: true
  69632. });
  69633. /**
  69634. * Attaches a new image processing configuration to the PBR Material.
  69635. * @param configuration
  69636. */
  69637. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  69638. var _this = this;
  69639. if (doNotBuild === void 0) { doNotBuild = false; }
  69640. if (configuration === this._imageProcessingConfiguration) {
  69641. return;
  69642. }
  69643. // Detaches observer.
  69644. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  69645. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  69646. }
  69647. // Pick the scene configuration if needed.
  69648. if (!configuration) {
  69649. var scene = null;
  69650. var engine = this.getEngine();
  69651. var camera = this.getCamera();
  69652. if (camera) {
  69653. scene = camera.getScene();
  69654. }
  69655. else if (engine && engine.scenes) {
  69656. var scenes = engine.scenes;
  69657. scene = scenes[scenes.length - 1];
  69658. }
  69659. else {
  69660. scene = BABYLON.Engine.LastCreatedScene;
  69661. }
  69662. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  69663. }
  69664. else {
  69665. this._imageProcessingConfiguration = configuration;
  69666. }
  69667. // Attaches observer.
  69668. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  69669. _this._updateParameters();
  69670. });
  69671. // Ensure the effect will be rebuilt.
  69672. if (!doNotBuild) {
  69673. this._updateParameters();
  69674. }
  69675. };
  69676. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  69677. /**
  69678. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  69679. */
  69680. get: function () {
  69681. return this.imageProcessingConfiguration.colorCurves;
  69682. },
  69683. /**
  69684. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  69685. */
  69686. set: function (value) {
  69687. this.imageProcessingConfiguration.colorCurves = value;
  69688. },
  69689. enumerable: true,
  69690. configurable: true
  69691. });
  69692. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  69693. /**
  69694. * Gets wether the color curves effect is enabled.
  69695. */
  69696. get: function () {
  69697. return this.imageProcessingConfiguration.colorCurvesEnabled;
  69698. },
  69699. /**
  69700. * Sets wether the color curves effect is enabled.
  69701. */
  69702. set: function (value) {
  69703. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  69704. },
  69705. enumerable: true,
  69706. configurable: true
  69707. });
  69708. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  69709. /**
  69710. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  69711. */
  69712. get: function () {
  69713. return this.imageProcessingConfiguration.colorGradingTexture;
  69714. },
  69715. /**
  69716. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  69717. */
  69718. set: function (value) {
  69719. this.imageProcessingConfiguration.colorGradingTexture = value;
  69720. },
  69721. enumerable: true,
  69722. configurable: true
  69723. });
  69724. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  69725. /**
  69726. * Gets wether the color grading effect is enabled.
  69727. */
  69728. get: function () {
  69729. return this.imageProcessingConfiguration.colorGradingEnabled;
  69730. },
  69731. /**
  69732. * Gets wether the color grading effect is enabled.
  69733. */
  69734. set: function (value) {
  69735. this.imageProcessingConfiguration.colorGradingEnabled = value;
  69736. },
  69737. enumerable: true,
  69738. configurable: true
  69739. });
  69740. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  69741. /**
  69742. * Gets exposure used in the effect.
  69743. */
  69744. get: function () {
  69745. return this.imageProcessingConfiguration.exposure;
  69746. },
  69747. /**
  69748. * Sets exposure used in the effect.
  69749. */
  69750. set: function (value) {
  69751. this.imageProcessingConfiguration.exposure = value;
  69752. },
  69753. enumerable: true,
  69754. configurable: true
  69755. });
  69756. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  69757. /**
  69758. * Gets wether tonemapping is enabled or not.
  69759. */
  69760. get: function () {
  69761. return this._imageProcessingConfiguration.toneMappingEnabled;
  69762. },
  69763. /**
  69764. * Sets wether tonemapping is enabled or not
  69765. */
  69766. set: function (value) {
  69767. this._imageProcessingConfiguration.toneMappingEnabled = value;
  69768. },
  69769. enumerable: true,
  69770. configurable: true
  69771. });
  69772. ;
  69773. ;
  69774. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  69775. /**
  69776. * Gets contrast used in the effect.
  69777. */
  69778. get: function () {
  69779. return this.imageProcessingConfiguration.contrast;
  69780. },
  69781. /**
  69782. * Sets contrast used in the effect.
  69783. */
  69784. set: function (value) {
  69785. this.imageProcessingConfiguration.contrast = value;
  69786. },
  69787. enumerable: true,
  69788. configurable: true
  69789. });
  69790. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  69791. /**
  69792. * Gets Vignette stretch size.
  69793. */
  69794. get: function () {
  69795. return this.imageProcessingConfiguration.vignetteStretch;
  69796. },
  69797. /**
  69798. * Sets Vignette stretch size.
  69799. */
  69800. set: function (value) {
  69801. this.imageProcessingConfiguration.vignetteStretch = value;
  69802. },
  69803. enumerable: true,
  69804. configurable: true
  69805. });
  69806. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  69807. /**
  69808. * Gets Vignette centre X Offset.
  69809. */
  69810. get: function () {
  69811. return this.imageProcessingConfiguration.vignetteCentreX;
  69812. },
  69813. /**
  69814. * Sets Vignette centre X Offset.
  69815. */
  69816. set: function (value) {
  69817. this.imageProcessingConfiguration.vignetteCentreX = value;
  69818. },
  69819. enumerable: true,
  69820. configurable: true
  69821. });
  69822. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  69823. /**
  69824. * Gets Vignette centre Y Offset.
  69825. */
  69826. get: function () {
  69827. return this.imageProcessingConfiguration.vignetteCentreY;
  69828. },
  69829. /**
  69830. * Sets Vignette centre Y Offset.
  69831. */
  69832. set: function (value) {
  69833. this.imageProcessingConfiguration.vignetteCentreY = value;
  69834. },
  69835. enumerable: true,
  69836. configurable: true
  69837. });
  69838. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  69839. /**
  69840. * Gets Vignette weight or intensity of the vignette effect.
  69841. */
  69842. get: function () {
  69843. return this.imageProcessingConfiguration.vignetteWeight;
  69844. },
  69845. /**
  69846. * Sets Vignette weight or intensity of the vignette effect.
  69847. */
  69848. set: function (value) {
  69849. this.imageProcessingConfiguration.vignetteWeight = value;
  69850. },
  69851. enumerable: true,
  69852. configurable: true
  69853. });
  69854. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  69855. /**
  69856. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  69857. * if vignetteEnabled is set to true.
  69858. */
  69859. get: function () {
  69860. return this.imageProcessingConfiguration.vignetteColor;
  69861. },
  69862. /**
  69863. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  69864. * if vignetteEnabled is set to true.
  69865. */
  69866. set: function (value) {
  69867. this.imageProcessingConfiguration.vignetteColor = value;
  69868. },
  69869. enumerable: true,
  69870. configurable: true
  69871. });
  69872. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  69873. /**
  69874. * Gets Camera field of view used by the Vignette effect.
  69875. */
  69876. get: function () {
  69877. return this.imageProcessingConfiguration.vignetteCameraFov;
  69878. },
  69879. /**
  69880. * Sets Camera field of view used by the Vignette effect.
  69881. */
  69882. set: function (value) {
  69883. this.imageProcessingConfiguration.vignetteCameraFov = value;
  69884. },
  69885. enumerable: true,
  69886. configurable: true
  69887. });
  69888. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  69889. /**
  69890. * Gets the vignette blend mode allowing different kind of effect.
  69891. */
  69892. get: function () {
  69893. return this.imageProcessingConfiguration.vignetteBlendMode;
  69894. },
  69895. /**
  69896. * Sets the vignette blend mode allowing different kind of effect.
  69897. */
  69898. set: function (value) {
  69899. this.imageProcessingConfiguration.vignetteBlendMode = value;
  69900. },
  69901. enumerable: true,
  69902. configurable: true
  69903. });
  69904. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  69905. /**
  69906. * Gets wether the vignette effect is enabled.
  69907. */
  69908. get: function () {
  69909. return this.imageProcessingConfiguration.vignetteEnabled;
  69910. },
  69911. /**
  69912. * Sets wether the vignette effect is enabled.
  69913. */
  69914. set: function (value) {
  69915. this.imageProcessingConfiguration.vignetteEnabled = value;
  69916. },
  69917. enumerable: true,
  69918. configurable: true
  69919. });
  69920. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  69921. /**
  69922. * Gets wether the input of the processing is in Gamma or Linear Space.
  69923. */
  69924. get: function () {
  69925. return this._fromLinearSpace;
  69926. },
  69927. /**
  69928. * Sets wether the input of the processing is in Gamma or Linear Space.
  69929. */
  69930. set: function (value) {
  69931. if (this._fromLinearSpace === value) {
  69932. return;
  69933. }
  69934. this._fromLinearSpace = value;
  69935. this._updateParameters();
  69936. },
  69937. enumerable: true,
  69938. configurable: true
  69939. });
  69940. ImageProcessingPostProcess.prototype.getClassName = function () {
  69941. return "ImageProcessingPostProcess";
  69942. };
  69943. ImageProcessingPostProcess.prototype._updateParameters = function () {
  69944. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  69945. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  69946. var defines = "";
  69947. for (var define in this._defines) {
  69948. if (this._defines[define]) {
  69949. defines += "#define " + define + ";\r\n";
  69950. }
  69951. }
  69952. var samplers = ["textureSampler"];
  69953. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  69954. var uniforms = ["scale"];
  69955. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  69956. this.updateEffect(defines, uniforms, samplers);
  69957. };
  69958. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  69959. _super.prototype.dispose.call(this, camera);
  69960. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  69961. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  69962. }
  69963. this.imageProcessingConfiguration.applyByPostProcess = false;
  69964. };
  69965. __decorate([
  69966. BABYLON.serialize()
  69967. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  69968. return ImageProcessingPostProcess;
  69969. }(BABYLON.PostProcess));
  69970. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  69971. })(BABYLON || (BABYLON = {}));
  69972. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  69973. var BABYLON;
  69974. (function (BABYLON) {
  69975. /**
  69976. * The Blur Post Process which blurs an image based on a kernel and direction.
  69977. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  69978. */
  69979. var BlurPostProcess = /** @class */ (function (_super) {
  69980. __extends(BlurPostProcess, _super);
  69981. /**
  69982. * Creates a new instance of @see BlurPostProcess
  69983. * @param name The name of the effect.
  69984. * @param direction The direction in which to blur the image.
  69985. * @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.
  69986. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  69987. * @param camera The camera to apply the render pass to.
  69988. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69989. * @param engine The engine which the post process will be applied. (default: current engine)
  69990. * @param reusable If the post process can be reused on the same frame. (default: false)
  69991. * @param textureType Type of textures used when performing the post process. (default: 0)
  69992. */
  69993. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines) {
  69994. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69995. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69996. if (defines === void 0) { defines = ""; }
  69997. 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;
  69998. _this.direction = direction;
  69999. _this._packedFloat = false;
  70000. _this._staticDefines = "";
  70001. _this._staticDefines = defines;
  70002. _this.onApplyObservable.add(function (effect) {
  70003. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  70004. });
  70005. _this.kernel = kernel;
  70006. return _this;
  70007. }
  70008. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  70009. /**
  70010. * Gets the length in pixels of the blur sample region
  70011. */
  70012. get: function () {
  70013. return this._idealKernel;
  70014. },
  70015. /**
  70016. * Sets the length in pixels of the blur sample region
  70017. */
  70018. set: function (v) {
  70019. if (this._idealKernel === v) {
  70020. return;
  70021. }
  70022. v = Math.max(v, 1);
  70023. this._idealKernel = v;
  70024. this._kernel = this._nearestBestKernel(v);
  70025. this._updateParameters();
  70026. },
  70027. enumerable: true,
  70028. configurable: true
  70029. });
  70030. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  70031. /**
  70032. * Gets wether or not the blur is unpacking/repacking floats
  70033. */
  70034. get: function () {
  70035. return this._packedFloat;
  70036. },
  70037. /**
  70038. * Sets wether or not the blur needs to unpack/repack floats
  70039. */
  70040. set: function (v) {
  70041. if (this._packedFloat === v) {
  70042. return;
  70043. }
  70044. this._packedFloat = v;
  70045. this._updateParameters();
  70046. },
  70047. enumerable: true,
  70048. configurable: true
  70049. });
  70050. BlurPostProcess.prototype._updateParameters = function () {
  70051. // Generate sampling offsets and weights
  70052. var N = this._kernel;
  70053. var centerIndex = (N - 1) / 2;
  70054. // Generate Gaussian sampling weights over kernel
  70055. var offsets = [];
  70056. var weights = [];
  70057. var totalWeight = 0;
  70058. for (var i = 0; i < N; i++) {
  70059. var u = i / (N - 1);
  70060. var w = this._gaussianWeight(u * 2.0 - 1);
  70061. offsets[i] = (i - centerIndex);
  70062. weights[i] = w;
  70063. totalWeight += w;
  70064. }
  70065. // Normalize weights
  70066. for (var i = 0; i < weights.length; i++) {
  70067. weights[i] /= totalWeight;
  70068. }
  70069. // Optimize: combine samples to take advantage of hardware linear sampling
  70070. // Walk from left to center, combining pairs (symmetrically)
  70071. var linearSamplingWeights = [];
  70072. var linearSamplingOffsets = [];
  70073. var linearSamplingMap = [];
  70074. for (var i = 0; i <= centerIndex; i += 2) {
  70075. var j = Math.min(i + 1, Math.floor(centerIndex));
  70076. var singleCenterSample = i === j;
  70077. if (singleCenterSample) {
  70078. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  70079. }
  70080. else {
  70081. var sharedCell = j === centerIndex;
  70082. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  70083. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  70084. if (offsetLinear === 0) {
  70085. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  70086. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  70087. }
  70088. else {
  70089. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  70090. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  70091. }
  70092. }
  70093. }
  70094. for (var i = 0; i < linearSamplingMap.length; i++) {
  70095. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  70096. linearSamplingWeights[i] = linearSamplingMap[i].w;
  70097. }
  70098. // Replace with optimized
  70099. offsets = linearSamplingOffsets;
  70100. weights = linearSamplingWeights;
  70101. // Generate shaders
  70102. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  70103. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  70104. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  70105. var defines = "";
  70106. defines += this._staticDefines;
  70107. for (var i = 0; i < varyingCount; i++) {
  70108. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  70109. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  70110. }
  70111. var depCount = 0;
  70112. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  70113. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  70114. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  70115. depCount++;
  70116. }
  70117. if (this.packedFloat) {
  70118. defines += "#define PACKEDFLOAT 1";
  70119. }
  70120. this.updateEffect(defines, null, null, {
  70121. varyingCount: varyingCount,
  70122. depCount: depCount
  70123. });
  70124. };
  70125. /**
  70126. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  70127. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  70128. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  70129. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  70130. * The gaps between physical kernels are compensated for in the weighting of the samples
  70131. * @param idealKernel Ideal blur kernel.
  70132. * @return Nearest best kernel.
  70133. */
  70134. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  70135. var v = Math.round(idealKernel);
  70136. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  70137. var k = _a[_i];
  70138. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  70139. return Math.max(k, 3);
  70140. }
  70141. }
  70142. return Math.max(v, 3);
  70143. };
  70144. /**
  70145. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  70146. * @param x The point on the Gaussian distribution to sample.
  70147. * @return the value of the Gaussian function at x.
  70148. */
  70149. BlurPostProcess.prototype._gaussianWeight = function (x) {
  70150. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  70151. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  70152. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  70153. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  70154. // truncated at around 1.3% of peak strength.
  70155. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  70156. var sigma = (1 / 3);
  70157. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  70158. var exponent = -((x * x) / (2.0 * sigma * sigma));
  70159. var weight = (1.0 / denominator) * Math.exp(exponent);
  70160. return weight;
  70161. };
  70162. /**
  70163. * Generates a string that can be used as a floating point number in GLSL.
  70164. * @param x Value to print.
  70165. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  70166. * @return GLSL float string.
  70167. */
  70168. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  70169. if (decimalFigures === void 0) { decimalFigures = 8; }
  70170. return x.toFixed(decimalFigures).replace(/0+$/, '');
  70171. };
  70172. return BlurPostProcess;
  70173. }(BABYLON.PostProcess));
  70174. BABYLON.BlurPostProcess = BlurPostProcess;
  70175. })(BABYLON || (BABYLON = {}));
  70176. //# sourceMappingURL=babylon.blurPostProcess.js.map
  70177. var BABYLON;
  70178. (function (BABYLON) {
  70179. /**
  70180. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  70181. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  70182. * based on samples that have a large difference in distance than the center pixel.
  70183. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  70184. */
  70185. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  70186. __extends(DepthOfFieldBlurPostProcess, _super);
  70187. /**
  70188. * Creates a new instance of @see CircleOfConfusionPostProcess
  70189. * @param name The name of the effect.
  70190. * @param scene The scene the effect belongs to.
  70191. * @param direction The direction the blur should be applied.
  70192. * @param kernel The size of the kernel used to blur.
  70193. * @param options The required width/height ratio to downsize to before computing the render pass.
  70194. * @param camera The camera to apply the render pass to.
  70195. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  70196. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  70197. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70198. * @param engine The engine which the post process will be applied. (default: current engine)
  70199. * @param reusable If the post process can be reused on the same frame. (default: false)
  70200. * @param textureType Type of textures used when performing the post process. (default: 0)
  70201. */
  70202. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType) {
  70203. if (imageToBlur === void 0) { imageToBlur = null; }
  70204. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70205. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70206. 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") || this;
  70207. _this.direction = direction;
  70208. _this.onApplyObservable.add(function (effect) {
  70209. if (imageToBlur != null) {
  70210. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  70211. }
  70212. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  70213. if (scene.activeCamera) {
  70214. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  70215. }
  70216. });
  70217. return _this;
  70218. }
  70219. return DepthOfFieldBlurPostProcess;
  70220. }(BABYLON.BlurPostProcess));
  70221. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  70222. })(BABYLON || (BABYLON = {}));
  70223. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  70224. var BABYLON;
  70225. (function (BABYLON) {
  70226. var Bone = /** @class */ (function (_super) {
  70227. __extends(Bone, _super);
  70228. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  70229. if (parentBone === void 0) { parentBone = null; }
  70230. if (localMatrix === void 0) { localMatrix = null; }
  70231. if (restPose === void 0) { restPose = null; }
  70232. if (baseMatrix === void 0) { baseMatrix = null; }
  70233. if (index === void 0) { index = null; }
  70234. var _this = _super.call(this, name, skeleton.getScene()) || this;
  70235. _this.name = name;
  70236. _this.children = new Array();
  70237. _this.animations = new Array();
  70238. // Set this value to map this bone to a different index in the transform matrices.
  70239. // Set this value to -1 to exclude the bone from the transform matrices.
  70240. _this._index = null;
  70241. _this._worldTransform = new BABYLON.Matrix();
  70242. _this._absoluteTransform = new BABYLON.Matrix();
  70243. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  70244. _this._scaleMatrix = BABYLON.Matrix.Identity();
  70245. _this._scaleVector = BABYLON.Vector3.One();
  70246. _this._negateScaleChildren = BABYLON.Vector3.One();
  70247. _this._scalingDeterminant = 1;
  70248. _this._skeleton = skeleton;
  70249. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  70250. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  70251. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  70252. _this._index = index;
  70253. skeleton.bones.push(_this);
  70254. _this.setParent(parentBone, false);
  70255. _this._updateDifferenceMatrix();
  70256. return _this;
  70257. }
  70258. Object.defineProperty(Bone.prototype, "_matrix", {
  70259. get: function () {
  70260. return this._localMatrix;
  70261. },
  70262. set: function (val) {
  70263. if (this._localMatrix) {
  70264. this._localMatrix.copyFrom(val);
  70265. }
  70266. else {
  70267. this._localMatrix = val;
  70268. }
  70269. },
  70270. enumerable: true,
  70271. configurable: true
  70272. });
  70273. // Members
  70274. Bone.prototype.getSkeleton = function () {
  70275. return this._skeleton;
  70276. };
  70277. Bone.prototype.getParent = function () {
  70278. return this._parent;
  70279. };
  70280. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  70281. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  70282. if (this._parent === parent) {
  70283. return;
  70284. }
  70285. if (this._parent) {
  70286. var index = this._parent.children.indexOf(this);
  70287. if (index !== -1) {
  70288. this._parent.children.splice(index, 1);
  70289. }
  70290. }
  70291. this._parent = parent;
  70292. if (this._parent) {
  70293. this._parent.children.push(this);
  70294. }
  70295. if (updateDifferenceMatrix) {
  70296. this._updateDifferenceMatrix();
  70297. }
  70298. };
  70299. Bone.prototype.getLocalMatrix = function () {
  70300. return this._localMatrix;
  70301. };
  70302. Bone.prototype.getBaseMatrix = function () {
  70303. return this._baseMatrix;
  70304. };
  70305. Bone.prototype.getRestPose = function () {
  70306. return this._restPose;
  70307. };
  70308. Bone.prototype.returnToRest = function () {
  70309. this.updateMatrix(this._restPose.clone());
  70310. };
  70311. Bone.prototype.getWorldMatrix = function () {
  70312. return this._worldTransform;
  70313. };
  70314. Bone.prototype.getInvertedAbsoluteTransform = function () {
  70315. return this._invertedAbsoluteTransform;
  70316. };
  70317. Bone.prototype.getAbsoluteTransform = function () {
  70318. return this._absoluteTransform;
  70319. };
  70320. Object.defineProperty(Bone.prototype, "position", {
  70321. // Properties (matches AbstractMesh properties)
  70322. get: function () {
  70323. return this.getPosition();
  70324. },
  70325. set: function (newPosition) {
  70326. this.setPosition(newPosition);
  70327. },
  70328. enumerable: true,
  70329. configurable: true
  70330. });
  70331. Object.defineProperty(Bone.prototype, "rotation", {
  70332. get: function () {
  70333. return this.getRotation();
  70334. },
  70335. set: function (newRotation) {
  70336. this.setRotation(newRotation);
  70337. },
  70338. enumerable: true,
  70339. configurable: true
  70340. });
  70341. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  70342. get: function () {
  70343. return this.getRotationQuaternion();
  70344. },
  70345. set: function (newRotation) {
  70346. this.setRotationQuaternion(newRotation);
  70347. },
  70348. enumerable: true,
  70349. configurable: true
  70350. });
  70351. Object.defineProperty(Bone.prototype, "scaling", {
  70352. get: function () {
  70353. return this.getScale();
  70354. },
  70355. set: function (newScaling) {
  70356. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  70357. },
  70358. enumerable: true,
  70359. configurable: true
  70360. });
  70361. // Methods
  70362. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  70363. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  70364. this._baseMatrix = matrix.clone();
  70365. this._localMatrix = matrix.clone();
  70366. this._skeleton._markAsDirty();
  70367. if (updateDifferenceMatrix) {
  70368. this._updateDifferenceMatrix();
  70369. }
  70370. };
  70371. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  70372. if (!rootMatrix) {
  70373. rootMatrix = this._baseMatrix;
  70374. }
  70375. if (this._parent) {
  70376. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  70377. }
  70378. else {
  70379. this._absoluteTransform.copyFrom(rootMatrix);
  70380. }
  70381. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  70382. for (var index = 0; index < this.children.length; index++) {
  70383. this.children[index]._updateDifferenceMatrix();
  70384. }
  70385. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  70386. };
  70387. Bone.prototype.markAsDirty = function () {
  70388. this._currentRenderId++;
  70389. this._skeleton._markAsDirty();
  70390. };
  70391. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  70392. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  70393. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  70394. // all animation may be coming from a library skeleton, so may need to create animation
  70395. if (this.animations.length === 0) {
  70396. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  70397. this.animations[0].setKeys([]);
  70398. }
  70399. // get animation info / verify there is such a range from the source bone
  70400. var sourceRange = source.animations[0].getRange(rangeName);
  70401. if (!sourceRange) {
  70402. return false;
  70403. }
  70404. var from = sourceRange.from;
  70405. var to = sourceRange.to;
  70406. var sourceKeys = source.animations[0].getKeys();
  70407. // rescaling prep
  70408. var sourceBoneLength = source.length;
  70409. var sourceParent = source.getParent();
  70410. var parent = this.getParent();
  70411. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  70412. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  70413. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  70414. var destKeys = this.animations[0].getKeys();
  70415. // loop vars declaration
  70416. var orig;
  70417. var origTranslation;
  70418. var mat;
  70419. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  70420. orig = sourceKeys[key];
  70421. if (orig.frame >= from && orig.frame <= to) {
  70422. if (rescaleAsRequired) {
  70423. mat = orig.value.clone();
  70424. // scale based on parent ratio, when bone has parent
  70425. if (parentScalingReqd) {
  70426. origTranslation = mat.getTranslation();
  70427. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  70428. // scale based on skeleton dimension ratio when root bone, and value is passed
  70429. }
  70430. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  70431. origTranslation = mat.getTranslation();
  70432. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  70433. // use original when root bone, and no data for skelDimensionsRatio
  70434. }
  70435. else {
  70436. mat = orig.value;
  70437. }
  70438. }
  70439. else {
  70440. mat = orig.value;
  70441. }
  70442. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  70443. }
  70444. }
  70445. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  70446. return true;
  70447. };
  70448. /**
  70449. * Translate the bone in local or world space.
  70450. * @param vec The amount to translate the bone.
  70451. * @param space The space that the translation is in.
  70452. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70453. */
  70454. Bone.prototype.translate = function (vec, space, mesh) {
  70455. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70456. var lm = this.getLocalMatrix();
  70457. if (space == BABYLON.Space.LOCAL) {
  70458. lm.m[12] += vec.x;
  70459. lm.m[13] += vec.y;
  70460. lm.m[14] += vec.z;
  70461. }
  70462. else {
  70463. var wm = null;
  70464. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70465. if (mesh) {
  70466. wm = mesh.getWorldMatrix();
  70467. }
  70468. this._skeleton.computeAbsoluteTransforms();
  70469. var tmat = Bone._tmpMats[0];
  70470. var tvec = Bone._tmpVecs[0];
  70471. if (this._parent) {
  70472. if (mesh && wm) {
  70473. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70474. tmat.multiplyToRef(wm, tmat);
  70475. }
  70476. else {
  70477. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70478. }
  70479. }
  70480. tmat.m[12] = 0;
  70481. tmat.m[13] = 0;
  70482. tmat.m[14] = 0;
  70483. tmat.invert();
  70484. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  70485. lm.m[12] += tvec.x;
  70486. lm.m[13] += tvec.y;
  70487. lm.m[14] += tvec.z;
  70488. }
  70489. this.markAsDirty();
  70490. };
  70491. /**
  70492. * Set the postion of the bone in local or world space.
  70493. * @param position The position to set the bone.
  70494. * @param space The space that the position is in.
  70495. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70496. */
  70497. Bone.prototype.setPosition = function (position, space, mesh) {
  70498. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70499. var lm = this.getLocalMatrix();
  70500. if (space == BABYLON.Space.LOCAL) {
  70501. lm.m[12] = position.x;
  70502. lm.m[13] = position.y;
  70503. lm.m[14] = position.z;
  70504. }
  70505. else {
  70506. var wm = null;
  70507. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70508. if (mesh) {
  70509. wm = mesh.getWorldMatrix();
  70510. }
  70511. this._skeleton.computeAbsoluteTransforms();
  70512. var tmat = Bone._tmpMats[0];
  70513. var vec = Bone._tmpVecs[0];
  70514. if (this._parent) {
  70515. if (mesh && wm) {
  70516. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70517. tmat.multiplyToRef(wm, tmat);
  70518. }
  70519. else {
  70520. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70521. }
  70522. }
  70523. tmat.invert();
  70524. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  70525. lm.m[12] = vec.x;
  70526. lm.m[13] = vec.y;
  70527. lm.m[14] = vec.z;
  70528. }
  70529. this.markAsDirty();
  70530. };
  70531. /**
  70532. * Set the absolute postion of the bone (world space).
  70533. * @param position The position to set the bone.
  70534. * @param mesh The mesh that this bone is attached to.
  70535. */
  70536. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  70537. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  70538. };
  70539. /**
  70540. * Set the scale of the bone on the x, y and z axes.
  70541. * @param x The scale of the bone on the x axis.
  70542. * @param x The scale of the bone on the y axis.
  70543. * @param z The scale of the bone on the z axis.
  70544. * @param scaleChildren Set this to true if children of the bone should be scaled.
  70545. */
  70546. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  70547. if (scaleChildren === void 0) { scaleChildren = false; }
  70548. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  70549. if (!scaleChildren) {
  70550. this._negateScaleChildren.x = 1 / x;
  70551. this._negateScaleChildren.y = 1 / y;
  70552. this._negateScaleChildren.z = 1 / z;
  70553. }
  70554. this._syncScaleVector();
  70555. }
  70556. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  70557. };
  70558. /**
  70559. * Scale the bone on the x, y and z axes.
  70560. * @param x The amount to scale the bone on the x axis.
  70561. * @param x The amount to scale the bone on the y axis.
  70562. * @param z The amount to scale the bone on the z axis.
  70563. * @param scaleChildren Set this to true if children of the bone should be scaled.
  70564. */
  70565. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  70566. if (scaleChildren === void 0) { scaleChildren = false; }
  70567. var locMat = this.getLocalMatrix();
  70568. var origLocMat = Bone._tmpMats[0];
  70569. origLocMat.copyFrom(locMat);
  70570. var origLocMatInv = Bone._tmpMats[1];
  70571. origLocMatInv.copyFrom(origLocMat);
  70572. origLocMatInv.invert();
  70573. var scaleMat = Bone._tmpMats[2];
  70574. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  70575. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  70576. this._scaleVector.x *= x;
  70577. this._scaleVector.y *= y;
  70578. this._scaleVector.z *= z;
  70579. locMat.multiplyToRef(origLocMatInv, locMat);
  70580. locMat.multiplyToRef(scaleMat, locMat);
  70581. locMat.multiplyToRef(origLocMat, locMat);
  70582. var parent = this.getParent();
  70583. if (parent) {
  70584. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  70585. }
  70586. else {
  70587. this.getAbsoluteTransform().copyFrom(locMat);
  70588. }
  70589. var len = this.children.length;
  70590. scaleMat.invert();
  70591. for (var i = 0; i < len; i++) {
  70592. var child = this.children[i];
  70593. var cm = child.getLocalMatrix();
  70594. cm.multiplyToRef(scaleMat, cm);
  70595. var lm = child.getLocalMatrix();
  70596. lm.m[12] *= x;
  70597. lm.m[13] *= y;
  70598. lm.m[14] *= z;
  70599. }
  70600. this.computeAbsoluteTransforms();
  70601. if (scaleChildren) {
  70602. for (var i = 0; i < len; i++) {
  70603. this.children[i].scale(x, y, z, scaleChildren);
  70604. }
  70605. }
  70606. this.markAsDirty();
  70607. };
  70608. /**
  70609. * Set the yaw, pitch, and roll of the bone in local or world space.
  70610. * @param yaw The rotation of the bone on the y axis.
  70611. * @param pitch The rotation of the bone on the x axis.
  70612. * @param roll The rotation of the bone on the z axis.
  70613. * @param space The space that the axes of rotation are in.
  70614. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70615. */
  70616. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  70617. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70618. var rotMat = Bone._tmpMats[0];
  70619. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  70620. var rotMatInv = Bone._tmpMats[1];
  70621. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70622. rotMatInv.multiplyToRef(rotMat, rotMat);
  70623. this._rotateWithMatrix(rotMat, space, mesh);
  70624. };
  70625. /**
  70626. * Rotate the bone on an axis in local or world space.
  70627. * @param axis The axis to rotate the bone on.
  70628. * @param amount The amount to rotate the bone.
  70629. * @param space The space that the axis is in.
  70630. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70631. */
  70632. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  70633. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70634. var rmat = Bone._tmpMats[0];
  70635. rmat.m[12] = 0;
  70636. rmat.m[13] = 0;
  70637. rmat.m[14] = 0;
  70638. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  70639. this._rotateWithMatrix(rmat, space, mesh);
  70640. };
  70641. /**
  70642. * Set the rotation of the bone to a particular axis angle in local or world space.
  70643. * @param axis The axis to rotate the bone on.
  70644. * @param angle The angle that the bone should be rotated to.
  70645. * @param space The space that the axis is in.
  70646. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70647. */
  70648. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  70649. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70650. var rotMat = Bone._tmpMats[0];
  70651. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  70652. var rotMatInv = Bone._tmpMats[1];
  70653. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70654. rotMatInv.multiplyToRef(rotMat, rotMat);
  70655. this._rotateWithMatrix(rotMat, space, mesh);
  70656. };
  70657. /**
  70658. * Set the euler rotation of the bone in local of world space.
  70659. * @param rotation The euler rotation that the bone should be set to.
  70660. * @param space The space that the rotation is in.
  70661. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70662. */
  70663. Bone.prototype.setRotation = function (rotation, space, mesh) {
  70664. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70665. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  70666. };
  70667. /**
  70668. * Set the quaternion rotation of the bone in local of world space.
  70669. * @param quat The quaternion rotation that the bone should be set to.
  70670. * @param space The space that the rotation is in.
  70671. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70672. */
  70673. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  70674. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70675. var rotMatInv = Bone._tmpMats[0];
  70676. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70677. var rotMat = Bone._tmpMats[1];
  70678. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  70679. rotMatInv.multiplyToRef(rotMat, rotMat);
  70680. this._rotateWithMatrix(rotMat, space, mesh);
  70681. };
  70682. /**
  70683. * Set the rotation matrix of the bone in local of world space.
  70684. * @param rotMat The rotation matrix that the bone should be set to.
  70685. * @param space The space that the rotation is in.
  70686. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70687. */
  70688. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  70689. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70690. var rotMatInv = Bone._tmpMats[0];
  70691. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70692. var rotMat2 = Bone._tmpMats[1];
  70693. rotMat2.copyFrom(rotMat);
  70694. rotMatInv.multiplyToRef(rotMat, rotMat2);
  70695. this._rotateWithMatrix(rotMat2, space, mesh);
  70696. };
  70697. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  70698. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70699. var lmat = this.getLocalMatrix();
  70700. var lx = lmat.m[12];
  70701. var ly = lmat.m[13];
  70702. var lz = lmat.m[14];
  70703. var parent = this.getParent();
  70704. var parentScale = Bone._tmpMats[3];
  70705. var parentScaleInv = Bone._tmpMats[4];
  70706. if (parent) {
  70707. if (space == BABYLON.Space.WORLD) {
  70708. if (mesh) {
  70709. parentScale.copyFrom(mesh.getWorldMatrix());
  70710. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  70711. }
  70712. else {
  70713. parentScale.copyFrom(parent.getAbsoluteTransform());
  70714. }
  70715. }
  70716. else {
  70717. parentScale = parent._scaleMatrix;
  70718. }
  70719. parentScaleInv.copyFrom(parentScale);
  70720. parentScaleInv.invert();
  70721. lmat.multiplyToRef(parentScale, lmat);
  70722. lmat.multiplyToRef(rmat, lmat);
  70723. lmat.multiplyToRef(parentScaleInv, lmat);
  70724. }
  70725. else {
  70726. if (space == BABYLON.Space.WORLD && mesh) {
  70727. parentScale.copyFrom(mesh.getWorldMatrix());
  70728. parentScaleInv.copyFrom(parentScale);
  70729. parentScaleInv.invert();
  70730. lmat.multiplyToRef(parentScale, lmat);
  70731. lmat.multiplyToRef(rmat, lmat);
  70732. lmat.multiplyToRef(parentScaleInv, lmat);
  70733. }
  70734. else {
  70735. lmat.multiplyToRef(rmat, lmat);
  70736. }
  70737. }
  70738. lmat.m[12] = lx;
  70739. lmat.m[13] = ly;
  70740. lmat.m[14] = lz;
  70741. this.computeAbsoluteTransforms();
  70742. this.markAsDirty();
  70743. };
  70744. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  70745. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70746. if (space == BABYLON.Space.WORLD) {
  70747. var scaleMatrix = Bone._tmpMats[2];
  70748. scaleMatrix.copyFrom(this._scaleMatrix);
  70749. rotMatInv.copyFrom(this.getAbsoluteTransform());
  70750. if (mesh) {
  70751. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  70752. var meshScale = Bone._tmpMats[3];
  70753. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  70754. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  70755. }
  70756. rotMatInv.invert();
  70757. scaleMatrix.m[0] *= this._scalingDeterminant;
  70758. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  70759. }
  70760. else {
  70761. rotMatInv.copyFrom(this.getLocalMatrix());
  70762. rotMatInv.invert();
  70763. var scaleMatrix = Bone._tmpMats[2];
  70764. scaleMatrix.copyFrom(this._scaleMatrix);
  70765. if (this._parent) {
  70766. var pscaleMatrix = Bone._tmpMats[3];
  70767. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  70768. pscaleMatrix.invert();
  70769. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  70770. }
  70771. else {
  70772. scaleMatrix.m[0] *= this._scalingDeterminant;
  70773. }
  70774. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  70775. }
  70776. };
  70777. /**
  70778. * Get the scale of the bone
  70779. * @returns the scale of the bone
  70780. */
  70781. Bone.prototype.getScale = function () {
  70782. return this._scaleVector.clone();
  70783. };
  70784. /**
  70785. * Copy the scale of the bone to a vector3.
  70786. * @param result The vector3 to copy the scale to
  70787. */
  70788. Bone.prototype.getScaleToRef = function (result) {
  70789. result.copyFrom(this._scaleVector);
  70790. };
  70791. /**
  70792. * Get the position of the bone in local or world space.
  70793. * @param space The space that the returned position is in.
  70794. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70795. * @returns The position of the bone
  70796. */
  70797. Bone.prototype.getPosition = function (space, mesh) {
  70798. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70799. if (mesh === void 0) { mesh = null; }
  70800. var pos = BABYLON.Vector3.Zero();
  70801. this.getPositionToRef(space, mesh, pos);
  70802. return pos;
  70803. };
  70804. /**
  70805. * Copy the position of the bone to a vector3 in local or world space.
  70806. * @param space The space that the returned position is in.
  70807. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70808. * @param result The vector3 to copy the position to.
  70809. */
  70810. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  70811. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70812. if (space == BABYLON.Space.LOCAL) {
  70813. var lm = this.getLocalMatrix();
  70814. result.x = lm.m[12];
  70815. result.y = lm.m[13];
  70816. result.z = lm.m[14];
  70817. }
  70818. else {
  70819. var wm = null;
  70820. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70821. if (mesh) {
  70822. wm = mesh.getWorldMatrix();
  70823. }
  70824. this._skeleton.computeAbsoluteTransforms();
  70825. var tmat = Bone._tmpMats[0];
  70826. if (mesh && wm) {
  70827. tmat.copyFrom(this.getAbsoluteTransform());
  70828. tmat.multiplyToRef(wm, tmat);
  70829. }
  70830. else {
  70831. tmat = this.getAbsoluteTransform();
  70832. }
  70833. result.x = tmat.m[12];
  70834. result.y = tmat.m[13];
  70835. result.z = tmat.m[14];
  70836. }
  70837. };
  70838. /**
  70839. * Get the absolute position of the bone (world space).
  70840. * @param mesh The mesh that this bone is attached to.
  70841. * @returns The absolute position of the bone
  70842. */
  70843. Bone.prototype.getAbsolutePosition = function (mesh) {
  70844. if (mesh === void 0) { mesh = null; }
  70845. var pos = BABYLON.Vector3.Zero();
  70846. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  70847. return pos;
  70848. };
  70849. /**
  70850. * Copy the absolute position of the bone (world space) to the result param.
  70851. * @param mesh The mesh that this bone is attached to.
  70852. * @param result The vector3 to copy the absolute position to.
  70853. */
  70854. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  70855. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  70856. };
  70857. /**
  70858. * Compute the absolute transforms of this bone and its children.
  70859. */
  70860. Bone.prototype.computeAbsoluteTransforms = function () {
  70861. if (this._parent) {
  70862. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  70863. }
  70864. else {
  70865. this._absoluteTransform.copyFrom(this._localMatrix);
  70866. var poseMatrix = this._skeleton.getPoseMatrix();
  70867. if (poseMatrix) {
  70868. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  70869. }
  70870. }
  70871. var children = this.children;
  70872. var len = children.length;
  70873. for (var i = 0; i < len; i++) {
  70874. children[i].computeAbsoluteTransforms();
  70875. }
  70876. };
  70877. Bone.prototype._syncScaleVector = function () {
  70878. var lm = this.getLocalMatrix();
  70879. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  70880. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  70881. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  70882. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  70883. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  70884. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  70885. this._scaleVector.x = xs * Math.sqrt(xsq);
  70886. this._scaleVector.y = ys * Math.sqrt(ysq);
  70887. this._scaleVector.z = zs * Math.sqrt(zsq);
  70888. if (this._parent) {
  70889. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  70890. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  70891. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  70892. }
  70893. BABYLON.Matrix.FromValuesToRef(this._scaleVector.x, 0, 0, 0, 0, this._scaleVector.y, 0, 0, 0, 0, this._scaleVector.z, 0, 0, 0, 0, 1, this._scaleMatrix);
  70894. };
  70895. /**
  70896. * Get the world direction from an axis that is in the local space of the bone.
  70897. * @param localAxis The local direction that is used to compute the world direction.
  70898. * @param mesh The mesh that this bone is attached to.
  70899. * @returns The world direction
  70900. */
  70901. Bone.prototype.getDirection = function (localAxis, mesh) {
  70902. if (mesh === void 0) { mesh = null; }
  70903. var result = BABYLON.Vector3.Zero();
  70904. this.getDirectionToRef(localAxis, mesh, result);
  70905. return result;
  70906. };
  70907. /**
  70908. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  70909. * @param localAxis The local direction that is used to compute the world direction.
  70910. * @param mesh The mesh that this bone is attached to.
  70911. * @param result The vector3 that the world direction will be copied to.
  70912. */
  70913. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  70914. if (mesh === void 0) { mesh = null; }
  70915. var wm = null;
  70916. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70917. if (mesh) {
  70918. wm = mesh.getWorldMatrix();
  70919. }
  70920. this._skeleton.computeAbsoluteTransforms();
  70921. var mat = Bone._tmpMats[0];
  70922. mat.copyFrom(this.getAbsoluteTransform());
  70923. if (mesh && wm) {
  70924. mat.multiplyToRef(wm, mat);
  70925. }
  70926. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  70927. result.normalize();
  70928. };
  70929. /**
  70930. * Get the euler rotation of the bone in local or world space.
  70931. * @param space The space that the rotation should be in.
  70932. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70933. * @returns The euler rotation
  70934. */
  70935. Bone.prototype.getRotation = function (space, mesh) {
  70936. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70937. if (mesh === void 0) { mesh = null; }
  70938. var result = BABYLON.Vector3.Zero();
  70939. this.getRotationToRef(space, mesh, result);
  70940. return result;
  70941. };
  70942. /**
  70943. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  70944. * @param space The space that the rotation should be in.
  70945. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70946. * @param result The vector3 that the rotation should be copied to.
  70947. */
  70948. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  70949. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70950. if (mesh === void 0) { mesh = null; }
  70951. var quat = Bone._tmpQuat;
  70952. this.getRotationQuaternionToRef(space, mesh, quat);
  70953. quat.toEulerAnglesToRef(result);
  70954. };
  70955. /**
  70956. * Get the quaternion rotation of the bone in either local or world space.
  70957. * @param space The space that the rotation should be in.
  70958. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70959. * @returns The quaternion rotation
  70960. */
  70961. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  70962. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70963. if (mesh === void 0) { mesh = null; }
  70964. var result = BABYLON.Quaternion.Identity();
  70965. this.getRotationQuaternionToRef(space, mesh, result);
  70966. return result;
  70967. };
  70968. /**
  70969. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  70970. * @param space The space that the rotation should be in.
  70971. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70972. * @param result The quaternion that the rotation should be copied to.
  70973. */
  70974. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  70975. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70976. if (mesh === void 0) { mesh = null; }
  70977. if (space == BABYLON.Space.LOCAL) {
  70978. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  70979. }
  70980. else {
  70981. var mat = Bone._tmpMats[0];
  70982. var amat = this.getAbsoluteTransform();
  70983. if (mesh) {
  70984. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  70985. }
  70986. else {
  70987. mat.copyFrom(amat);
  70988. }
  70989. mat.m[0] *= this._scalingDeterminant;
  70990. mat.m[1] *= this._scalingDeterminant;
  70991. mat.m[2] *= this._scalingDeterminant;
  70992. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  70993. }
  70994. };
  70995. /**
  70996. * Get the rotation matrix of the bone in local or world space.
  70997. * @param space The space that the rotation should be in.
  70998. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70999. * @returns The rotation matrix
  71000. */
  71001. Bone.prototype.getRotationMatrix = function (space, mesh) {
  71002. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71003. var result = BABYLON.Matrix.Identity();
  71004. this.getRotationMatrixToRef(space, mesh, result);
  71005. return result;
  71006. };
  71007. /**
  71008. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  71009. * @param space The space that the rotation should be in.
  71010. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71011. * @param result The quaternion that the rotation should be copied to.
  71012. */
  71013. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  71014. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71015. if (space == BABYLON.Space.LOCAL) {
  71016. this.getLocalMatrix().getRotationMatrixToRef(result);
  71017. }
  71018. else {
  71019. var mat = Bone._tmpMats[0];
  71020. var amat = this.getAbsoluteTransform();
  71021. if (mesh) {
  71022. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  71023. }
  71024. else {
  71025. mat.copyFrom(amat);
  71026. }
  71027. mat.m[0] *= this._scalingDeterminant;
  71028. mat.m[1] *= this._scalingDeterminant;
  71029. mat.m[2] *= this._scalingDeterminant;
  71030. mat.getRotationMatrixToRef(result);
  71031. }
  71032. };
  71033. /**
  71034. * Get the world position of a point that is in the local space of the bone.
  71035. * @param position The local position
  71036. * @param mesh The mesh that this bone is attached to.
  71037. * @returns The world position
  71038. */
  71039. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  71040. if (mesh === void 0) { mesh = null; }
  71041. var result = BABYLON.Vector3.Zero();
  71042. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  71043. return result;
  71044. };
  71045. /**
  71046. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  71047. * @param position The local position
  71048. * @param mesh The mesh that this bone is attached to.
  71049. * @param result The vector3 that the world position should be copied to.
  71050. */
  71051. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  71052. if (mesh === void 0) { mesh = null; }
  71053. var wm = null;
  71054. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71055. if (mesh) {
  71056. wm = mesh.getWorldMatrix();
  71057. }
  71058. this._skeleton.computeAbsoluteTransforms();
  71059. var tmat = Bone._tmpMats[0];
  71060. if (mesh && wm) {
  71061. tmat.copyFrom(this.getAbsoluteTransform());
  71062. tmat.multiplyToRef(wm, tmat);
  71063. }
  71064. else {
  71065. tmat = this.getAbsoluteTransform();
  71066. }
  71067. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  71068. };
  71069. /**
  71070. * Get the local position of a point that is in world space.
  71071. * @param position The world position
  71072. * @param mesh The mesh that this bone is attached to.
  71073. * @returns The local position
  71074. */
  71075. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  71076. if (mesh === void 0) { mesh = null; }
  71077. var result = BABYLON.Vector3.Zero();
  71078. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  71079. return result;
  71080. };
  71081. /**
  71082. * Get the local position of a point that is in world space and copy it to the result param.
  71083. * @param position The world position
  71084. * @param mesh The mesh that this bone is attached to.
  71085. * @param result The vector3 that the local position should be copied to.
  71086. */
  71087. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  71088. if (mesh === void 0) { mesh = null; }
  71089. var wm = null;
  71090. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71091. if (mesh) {
  71092. wm = mesh.getWorldMatrix();
  71093. }
  71094. this._skeleton.computeAbsoluteTransforms();
  71095. var tmat = Bone._tmpMats[0];
  71096. tmat.copyFrom(this.getAbsoluteTransform());
  71097. if (mesh && wm) {
  71098. tmat.multiplyToRef(wm, tmat);
  71099. }
  71100. tmat.invert();
  71101. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  71102. };
  71103. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71104. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  71105. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  71106. return Bone;
  71107. }(BABYLON.Node));
  71108. BABYLON.Bone = Bone;
  71109. })(BABYLON || (BABYLON = {}));
  71110. //# sourceMappingURL=babylon.bone.js.map
  71111. var BABYLON;
  71112. (function (BABYLON) {
  71113. var BoneIKController = /** @class */ (function () {
  71114. function BoneIKController(mesh, bone, options) {
  71115. this.targetPosition = BABYLON.Vector3.Zero();
  71116. this.poleTargetPosition = BABYLON.Vector3.Zero();
  71117. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  71118. this.poleAngle = 0;
  71119. this.slerpAmount = 1;
  71120. this._bone1Quat = BABYLON.Quaternion.Identity();
  71121. this._bone1Mat = BABYLON.Matrix.Identity();
  71122. this._bone2Ang = Math.PI;
  71123. this._maxAngle = Math.PI;
  71124. this._rightHandedSystem = false;
  71125. this._bendAxis = BABYLON.Vector3.Right();
  71126. this._slerping = false;
  71127. this._adjustRoll = 0;
  71128. this._bone2 = bone;
  71129. this._bone1 = bone.getParent();
  71130. if (!this._bone1) {
  71131. return;
  71132. }
  71133. this.mesh = mesh;
  71134. var bonePos = bone.getPosition();
  71135. if (bone.getAbsoluteTransform().determinant() > 0) {
  71136. this._rightHandedSystem = true;
  71137. this._bendAxis.x = 0;
  71138. this._bendAxis.y = 0;
  71139. this._bendAxis.z = -1;
  71140. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  71141. this._adjustRoll = Math.PI * .5;
  71142. this._bendAxis.z = 1;
  71143. }
  71144. }
  71145. if (this._bone1.length) {
  71146. var boneScale1 = this._bone1.getScale();
  71147. var boneScale2 = this._bone2.getScale();
  71148. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  71149. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  71150. }
  71151. else if (this._bone1.children[0]) {
  71152. mesh.computeWorldMatrix(true);
  71153. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  71154. var pos2 = this._bone2.getAbsolutePosition(mesh);
  71155. var pos3 = this._bone1.getAbsolutePosition(mesh);
  71156. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  71157. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  71158. }
  71159. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  71160. this.maxAngle = Math.PI;
  71161. if (options) {
  71162. if (options.targetMesh) {
  71163. this.targetMesh = options.targetMesh;
  71164. this.targetMesh.computeWorldMatrix(true);
  71165. }
  71166. if (options.poleTargetMesh) {
  71167. this.poleTargetMesh = options.poleTargetMesh;
  71168. this.poleTargetMesh.computeWorldMatrix(true);
  71169. }
  71170. else if (options.poleTargetBone) {
  71171. this.poleTargetBone = options.poleTargetBone;
  71172. }
  71173. else if (this._bone1.getParent()) {
  71174. this.poleTargetBone = this._bone1.getParent();
  71175. }
  71176. if (options.poleTargetLocalOffset) {
  71177. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  71178. }
  71179. if (options.poleAngle) {
  71180. this.poleAngle = options.poleAngle;
  71181. }
  71182. if (options.bendAxis) {
  71183. this._bendAxis.copyFrom(options.bendAxis);
  71184. }
  71185. if (options.maxAngle) {
  71186. this.maxAngle = options.maxAngle;
  71187. }
  71188. if (options.slerpAmount) {
  71189. this.slerpAmount = options.slerpAmount;
  71190. }
  71191. }
  71192. }
  71193. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  71194. get: function () {
  71195. return this._maxAngle;
  71196. },
  71197. set: function (value) {
  71198. this._setMaxAngle(value);
  71199. },
  71200. enumerable: true,
  71201. configurable: true
  71202. });
  71203. BoneIKController.prototype._setMaxAngle = function (ang) {
  71204. if (ang < 0) {
  71205. ang = 0;
  71206. }
  71207. if (ang > Math.PI || ang == undefined) {
  71208. ang = Math.PI;
  71209. }
  71210. this._maxAngle = ang;
  71211. var a = this._bone1Length;
  71212. var b = this._bone2Length;
  71213. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  71214. };
  71215. BoneIKController.prototype.update = function () {
  71216. var bone1 = this._bone1;
  71217. if (!bone1) {
  71218. return;
  71219. }
  71220. var target = this.targetPosition;
  71221. var poleTarget = this.poleTargetPosition;
  71222. var mat1 = BoneIKController._tmpMats[0];
  71223. var mat2 = BoneIKController._tmpMats[1];
  71224. if (this.targetMesh) {
  71225. target.copyFrom(this.targetMesh.getAbsolutePosition());
  71226. }
  71227. if (this.poleTargetBone) {
  71228. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  71229. }
  71230. else if (this.poleTargetMesh) {
  71231. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  71232. }
  71233. var bonePos = BoneIKController._tmpVecs[0];
  71234. var zaxis = BoneIKController._tmpVecs[1];
  71235. var xaxis = BoneIKController._tmpVecs[2];
  71236. var yaxis = BoneIKController._tmpVecs[3];
  71237. var upAxis = BoneIKController._tmpVecs[4];
  71238. var _tmpQuat = BoneIKController._tmpQuat;
  71239. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  71240. poleTarget.subtractToRef(bonePos, upAxis);
  71241. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  71242. upAxis.y = 1;
  71243. }
  71244. else {
  71245. upAxis.normalize();
  71246. }
  71247. target.subtractToRef(bonePos, yaxis);
  71248. yaxis.normalize();
  71249. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  71250. zaxis.normalize();
  71251. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  71252. xaxis.normalize();
  71253. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  71254. var a = this._bone1Length;
  71255. var b = this._bone2Length;
  71256. var c = BABYLON.Vector3.Distance(bonePos, target);
  71257. if (this._maxReach > 0) {
  71258. c = Math.min(this._maxReach, c);
  71259. }
  71260. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  71261. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  71262. if (acosa > 1) {
  71263. acosa = 1;
  71264. }
  71265. if (acosb > 1) {
  71266. acosb = 1;
  71267. }
  71268. if (acosa < -1) {
  71269. acosa = -1;
  71270. }
  71271. if (acosb < -1) {
  71272. acosb = -1;
  71273. }
  71274. var angA = Math.acos(acosa);
  71275. var angB = Math.acos(acosb);
  71276. var angC = -angA - angB;
  71277. if (this._rightHandedSystem) {
  71278. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  71279. mat2.multiplyToRef(mat1, mat1);
  71280. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  71281. mat2.multiplyToRef(mat1, mat1);
  71282. }
  71283. else {
  71284. var _tmpVec = BoneIKController._tmpVecs[5];
  71285. _tmpVec.copyFrom(this._bendAxis);
  71286. _tmpVec.x *= -1;
  71287. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  71288. mat2.multiplyToRef(mat1, mat1);
  71289. }
  71290. if (this.poleAngle) {
  71291. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  71292. mat1.multiplyToRef(mat2, mat1);
  71293. }
  71294. if (this._bone1) {
  71295. if (this.slerpAmount < 1) {
  71296. if (!this._slerping) {
  71297. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  71298. }
  71299. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  71300. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  71301. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  71302. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  71303. this._slerping = true;
  71304. }
  71305. else {
  71306. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  71307. this._bone1Mat.copyFrom(mat1);
  71308. this._slerping = false;
  71309. }
  71310. }
  71311. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  71312. this._bone2Ang = angC;
  71313. };
  71314. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71315. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  71316. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  71317. return BoneIKController;
  71318. }());
  71319. BABYLON.BoneIKController = BoneIKController;
  71320. })(BABYLON || (BABYLON = {}));
  71321. //# sourceMappingURL=babylon.boneIKController.js.map
  71322. var BABYLON;
  71323. (function (BABYLON) {
  71324. var BoneLookController = /** @class */ (function () {
  71325. /**
  71326. * Create a BoneLookController
  71327. * @param mesh the mesh that the bone belongs to
  71328. * @param bone the bone that will be looking to the target
  71329. * @param target the target Vector3 to look at
  71330. * @param settings optional settings:
  71331. * - maxYaw: the maximum angle the bone will yaw to
  71332. * - minYaw: the minimum angle the bone will yaw to
  71333. * - maxPitch: the maximum angle the bone will pitch to
  71334. * - minPitch: the minimum angle the bone will yaw to
  71335. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  71336. * - upAxis: the up axis of the coordinate system
  71337. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  71338. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  71339. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  71340. * - adjustYaw: used to make an adjustment to the yaw of the bone
  71341. * - adjustPitch: used to make an adjustment to the pitch of the bone
  71342. * - adjustRoll: used to make an adjustment to the roll of the bone
  71343. **/
  71344. function BoneLookController(mesh, bone, target, options) {
  71345. /**
  71346. * The up axis of the coordinate system that is used when the bone is rotated.
  71347. */
  71348. this.upAxis = BABYLON.Vector3.Up();
  71349. /**
  71350. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  71351. */
  71352. this.upAxisSpace = BABYLON.Space.LOCAL;
  71353. /**
  71354. * Used to make an adjustment to the yaw of the bone.
  71355. */
  71356. this.adjustYaw = 0;
  71357. /**
  71358. * Used to make an adjustment to the pitch of the bone.
  71359. */
  71360. this.adjustPitch = 0;
  71361. /**
  71362. * Used to make an adjustment to the roll of the bone.
  71363. */
  71364. this.adjustRoll = 0;
  71365. /**
  71366. * 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).
  71367. */
  71368. this.slerpAmount = 1;
  71369. this._boneQuat = BABYLON.Quaternion.Identity();
  71370. this._slerping = false;
  71371. this._firstFrameSkipped = false;
  71372. this._fowardAxis = BABYLON.Vector3.Forward();
  71373. this.mesh = mesh;
  71374. this.bone = bone;
  71375. this.target = target;
  71376. if (options) {
  71377. if (options.adjustYaw) {
  71378. this.adjustYaw = options.adjustYaw;
  71379. }
  71380. if (options.adjustPitch) {
  71381. this.adjustPitch = options.adjustPitch;
  71382. }
  71383. if (options.adjustRoll) {
  71384. this.adjustRoll = options.adjustRoll;
  71385. }
  71386. if (options.maxYaw != null) {
  71387. this.maxYaw = options.maxYaw;
  71388. }
  71389. else {
  71390. this.maxYaw = Math.PI;
  71391. }
  71392. if (options.minYaw != null) {
  71393. this.minYaw = options.minYaw;
  71394. }
  71395. else {
  71396. this.minYaw = -Math.PI;
  71397. }
  71398. if (options.maxPitch != null) {
  71399. this.maxPitch = options.maxPitch;
  71400. }
  71401. else {
  71402. this.maxPitch = Math.PI;
  71403. }
  71404. if (options.minPitch != null) {
  71405. this.minPitch = options.minPitch;
  71406. }
  71407. else {
  71408. this.minPitch = -Math.PI;
  71409. }
  71410. if (options.slerpAmount != null) {
  71411. this.slerpAmount = options.slerpAmount;
  71412. }
  71413. if (options.upAxis != null) {
  71414. this.upAxis = options.upAxis;
  71415. }
  71416. if (options.upAxisSpace != null) {
  71417. this.upAxisSpace = options.upAxisSpace;
  71418. }
  71419. if (options.yawAxis != null || options.pitchAxis != null) {
  71420. var newYawAxis = BABYLON.Axis.Y;
  71421. var newPitchAxis = BABYLON.Axis.X;
  71422. if (options.yawAxis != null) {
  71423. newYawAxis = options.yawAxis.clone();
  71424. newYawAxis.normalize();
  71425. }
  71426. if (options.pitchAxis != null) {
  71427. newPitchAxis = options.pitchAxis.clone();
  71428. newPitchAxis.normalize();
  71429. }
  71430. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  71431. this._transformYawPitch = BABYLON.Matrix.Identity();
  71432. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  71433. this._transformYawPitchInv = this._transformYawPitch.clone();
  71434. this._transformYawPitch.invert();
  71435. }
  71436. }
  71437. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  71438. this.upAxisSpace = BABYLON.Space.LOCAL;
  71439. }
  71440. }
  71441. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  71442. /**
  71443. * Get/set the minimum yaw angle that the bone can look to.
  71444. */
  71445. get: function () {
  71446. return this._minYaw;
  71447. },
  71448. set: function (value) {
  71449. this._minYaw = value;
  71450. this._minYawSin = Math.sin(value);
  71451. this._minYawCos = Math.cos(value);
  71452. if (this._maxYaw != null) {
  71453. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  71454. this._yawRange = this._maxYaw - this._minYaw;
  71455. }
  71456. },
  71457. enumerable: true,
  71458. configurable: true
  71459. });
  71460. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  71461. /**
  71462. * Get/set the maximum yaw angle that the bone can look to.
  71463. */
  71464. get: function () {
  71465. return this._maxYaw;
  71466. },
  71467. set: function (value) {
  71468. this._maxYaw = value;
  71469. this._maxYawSin = Math.sin(value);
  71470. this._maxYawCos = Math.cos(value);
  71471. if (this._minYaw != null) {
  71472. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  71473. this._yawRange = this._maxYaw - this._minYaw;
  71474. }
  71475. },
  71476. enumerable: true,
  71477. configurable: true
  71478. });
  71479. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  71480. /**
  71481. * Get/set the minimum pitch angle that the bone can look to.
  71482. */
  71483. get: function () {
  71484. return this._minPitch;
  71485. },
  71486. set: function (value) {
  71487. this._minPitch = value;
  71488. this._minPitchTan = Math.tan(value);
  71489. },
  71490. enumerable: true,
  71491. configurable: true
  71492. });
  71493. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  71494. /**
  71495. * Get/set the maximum pitch angle that the bone can look to.
  71496. */
  71497. get: function () {
  71498. return this._maxPitch;
  71499. },
  71500. set: function (value) {
  71501. this._maxPitch = value;
  71502. this._maxPitchTan = Math.tan(value);
  71503. },
  71504. enumerable: true,
  71505. configurable: true
  71506. });
  71507. /**
  71508. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  71509. */
  71510. BoneLookController.prototype.update = function () {
  71511. //skip the first frame when slerping so that the mesh rotation is correct
  71512. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  71513. this._firstFrameSkipped = true;
  71514. return;
  71515. }
  71516. var bone = this.bone;
  71517. var bonePos = BoneLookController._tmpVecs[0];
  71518. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  71519. var target = this.target;
  71520. var _tmpMat1 = BoneLookController._tmpMats[0];
  71521. var _tmpMat2 = BoneLookController._tmpMats[1];
  71522. var mesh = this.mesh;
  71523. var parentBone = bone.getParent();
  71524. var upAxis = BoneLookController._tmpVecs[1];
  71525. upAxis.copyFrom(this.upAxis);
  71526. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  71527. if (this._transformYawPitch) {
  71528. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  71529. }
  71530. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  71531. }
  71532. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  71533. mesh.getDirectionToRef(upAxis, upAxis);
  71534. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  71535. upAxis.normalize();
  71536. }
  71537. }
  71538. var checkYaw = false;
  71539. var checkPitch = false;
  71540. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  71541. checkYaw = true;
  71542. }
  71543. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  71544. checkPitch = true;
  71545. }
  71546. if (checkYaw || checkPitch) {
  71547. var spaceMat = BoneLookController._tmpMats[2];
  71548. var spaceMatInv = BoneLookController._tmpMats[3];
  71549. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  71550. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  71551. }
  71552. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  71553. spaceMat.copyFrom(mesh.getWorldMatrix());
  71554. }
  71555. else {
  71556. var forwardAxis = BoneLookController._tmpVecs[2];
  71557. forwardAxis.copyFrom(this._fowardAxis);
  71558. if (this._transformYawPitch) {
  71559. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  71560. }
  71561. if (parentBone) {
  71562. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  71563. }
  71564. else {
  71565. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  71566. }
  71567. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  71568. rightAxis.normalize();
  71569. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  71570. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  71571. }
  71572. spaceMat.invertToRef(spaceMatInv);
  71573. var xzlen = null;
  71574. if (checkPitch) {
  71575. var localTarget = BoneLookController._tmpVecs[3];
  71576. target.subtractToRef(bonePos, localTarget);
  71577. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  71578. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71579. var pitch = Math.atan2(localTarget.y, xzlen);
  71580. var newPitch = pitch;
  71581. if (pitch > this._maxPitch) {
  71582. localTarget.y = this._maxPitchTan * xzlen;
  71583. newPitch = this._maxPitch;
  71584. }
  71585. else if (pitch < this._minPitch) {
  71586. localTarget.y = this._minPitchTan * xzlen;
  71587. newPitch = this._minPitch;
  71588. }
  71589. if (pitch != newPitch) {
  71590. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  71591. localTarget.addInPlace(bonePos);
  71592. target = localTarget;
  71593. }
  71594. }
  71595. if (checkYaw) {
  71596. var localTarget = BoneLookController._tmpVecs[4];
  71597. target.subtractToRef(bonePos, localTarget);
  71598. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  71599. var yaw = Math.atan2(localTarget.x, localTarget.z);
  71600. var newYaw = yaw;
  71601. if (yaw > this._maxYaw || yaw < this._minYaw) {
  71602. if (xzlen == null) {
  71603. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71604. }
  71605. if (this._yawRange > Math.PI) {
  71606. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  71607. localTarget.z = this._maxYawCos * xzlen;
  71608. localTarget.x = this._maxYawSin * xzlen;
  71609. newYaw = this._maxYaw;
  71610. }
  71611. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  71612. localTarget.z = this._minYawCos * xzlen;
  71613. localTarget.x = this._minYawSin * xzlen;
  71614. newYaw = this._minYaw;
  71615. }
  71616. }
  71617. else {
  71618. if (yaw > this._maxYaw) {
  71619. localTarget.z = this._maxYawCos * xzlen;
  71620. localTarget.x = this._maxYawSin * xzlen;
  71621. newYaw = this._maxYaw;
  71622. }
  71623. else if (yaw < this._minYaw) {
  71624. localTarget.z = this._minYawCos * xzlen;
  71625. localTarget.x = this._minYawSin * xzlen;
  71626. newYaw = this._minYaw;
  71627. }
  71628. }
  71629. }
  71630. if (this._slerping && this._yawRange > Math.PI) {
  71631. //are we going to be crossing into the min/max region?
  71632. var boneFwd = BoneLookController._tmpVecs[8];
  71633. boneFwd.copyFrom(BABYLON.Axis.Z);
  71634. if (this._transformYawPitch) {
  71635. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  71636. }
  71637. var boneRotMat = BoneLookController._tmpMats[4];
  71638. this._boneQuat.toRotationMatrix(boneRotMat);
  71639. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  71640. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  71641. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  71642. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  71643. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  71644. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  71645. if (angBtwTar > angBtwMidYaw) {
  71646. if (xzlen == null) {
  71647. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71648. }
  71649. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  71650. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  71651. if (angBtwMin < angBtwMax) {
  71652. newYaw = boneYaw + Math.PI * .75;
  71653. localTarget.z = Math.cos(newYaw) * xzlen;
  71654. localTarget.x = Math.sin(newYaw) * xzlen;
  71655. }
  71656. else {
  71657. newYaw = boneYaw - Math.PI * .75;
  71658. localTarget.z = Math.cos(newYaw) * xzlen;
  71659. localTarget.x = Math.sin(newYaw) * xzlen;
  71660. }
  71661. }
  71662. }
  71663. if (yaw != newYaw) {
  71664. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  71665. localTarget.addInPlace(bonePos);
  71666. target = localTarget;
  71667. }
  71668. }
  71669. }
  71670. var zaxis = BoneLookController._tmpVecs[5];
  71671. var xaxis = BoneLookController._tmpVecs[6];
  71672. var yaxis = BoneLookController._tmpVecs[7];
  71673. var _tmpQuat = BoneLookController._tmpQuat;
  71674. target.subtractToRef(bonePos, zaxis);
  71675. zaxis.normalize();
  71676. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  71677. xaxis.normalize();
  71678. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  71679. yaxis.normalize();
  71680. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  71681. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  71682. return;
  71683. }
  71684. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  71685. return;
  71686. }
  71687. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  71688. return;
  71689. }
  71690. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  71691. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  71692. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  71693. }
  71694. if (this.slerpAmount < 1) {
  71695. if (!this._slerping) {
  71696. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  71697. }
  71698. if (this._transformYawPitch) {
  71699. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  71700. }
  71701. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  71702. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  71703. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  71704. this._slerping = true;
  71705. }
  71706. else {
  71707. if (this._transformYawPitch) {
  71708. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  71709. }
  71710. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  71711. this._slerping = false;
  71712. }
  71713. };
  71714. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  71715. var angDiff = ang2 - ang1;
  71716. angDiff %= Math.PI * 2;
  71717. if (angDiff > Math.PI) {
  71718. angDiff -= Math.PI * 2;
  71719. }
  71720. else if (angDiff < -Math.PI) {
  71721. angDiff += Math.PI * 2;
  71722. }
  71723. return angDiff;
  71724. };
  71725. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  71726. ang1 %= (2 * Math.PI);
  71727. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  71728. ang2 %= (2 * Math.PI);
  71729. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  71730. var ab = 0;
  71731. if (ang1 < ang2) {
  71732. ab = ang2 - ang1;
  71733. }
  71734. else {
  71735. ab = ang1 - ang2;
  71736. }
  71737. if (ab > Math.PI) {
  71738. ab = Math.PI * 2 - ab;
  71739. }
  71740. return ab;
  71741. };
  71742. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  71743. ang %= (2 * Math.PI);
  71744. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  71745. ang1 %= (2 * Math.PI);
  71746. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  71747. ang2 %= (2 * Math.PI);
  71748. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  71749. if (ang1 < ang2) {
  71750. if (ang > ang1 && ang < ang2) {
  71751. return true;
  71752. }
  71753. }
  71754. else {
  71755. if (ang > ang2 && ang < ang1) {
  71756. return true;
  71757. }
  71758. }
  71759. return false;
  71760. };
  71761. 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()];
  71762. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  71763. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  71764. return BoneLookController;
  71765. }());
  71766. BABYLON.BoneLookController = BoneLookController;
  71767. })(BABYLON || (BABYLON = {}));
  71768. //# sourceMappingURL=babylon.boneLookController.js.map
  71769. var BABYLON;
  71770. (function (BABYLON) {
  71771. var Skeleton = /** @class */ (function () {
  71772. function Skeleton(name, id, scene) {
  71773. this.name = name;
  71774. this.id = id;
  71775. this.bones = new Array();
  71776. this.needInitialSkinMatrix = false;
  71777. this._isDirty = true;
  71778. this._meshesWithPoseMatrix = new Array();
  71779. this._identity = BABYLON.Matrix.Identity();
  71780. this._ranges = {};
  71781. this._lastAbsoluteTransformsUpdateId = -1;
  71782. /**
  71783. * Specifies if the skeleton should be serialized.
  71784. */
  71785. this.doNotSerialize = false;
  71786. // Events
  71787. /**
  71788. * An event triggered before computing the skeleton's matrices
  71789. * @type {BABYLON.Observable}
  71790. */
  71791. this.onBeforeComputeObservable = new BABYLON.Observable();
  71792. this.bones = [];
  71793. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  71794. scene.skeletons.push(this);
  71795. //make sure it will recalculate the matrix next time prepare is called.
  71796. this._isDirty = true;
  71797. }
  71798. // Members
  71799. Skeleton.prototype.getTransformMatrices = function (mesh) {
  71800. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  71801. return mesh._bonesTransformMatrices;
  71802. }
  71803. if (!this._transformMatrices) {
  71804. this.prepare();
  71805. }
  71806. return this._transformMatrices;
  71807. };
  71808. Skeleton.prototype.getScene = function () {
  71809. return this._scene;
  71810. };
  71811. // Methods
  71812. /**
  71813. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  71814. */
  71815. Skeleton.prototype.toString = function (fullDetails) {
  71816. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  71817. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  71818. if (fullDetails) {
  71819. ret += ", Ranges: {";
  71820. var first = true;
  71821. for (var name_1 in this._ranges) {
  71822. if (first) {
  71823. ret += ", ";
  71824. first = false;
  71825. }
  71826. ret += name_1;
  71827. }
  71828. ret += "}";
  71829. }
  71830. return ret;
  71831. };
  71832. /**
  71833. * Get bone's index searching by name
  71834. * @param {string} name is bone's name to search for
  71835. * @return {number} Indice of the bone. Returns -1 if not found
  71836. */
  71837. Skeleton.prototype.getBoneIndexByName = function (name) {
  71838. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  71839. if (this.bones[boneIndex].name === name) {
  71840. return boneIndex;
  71841. }
  71842. }
  71843. return -1;
  71844. };
  71845. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  71846. // check name not already in use
  71847. if (!this._ranges[name]) {
  71848. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  71849. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  71850. if (this.bones[i].animations[0]) {
  71851. this.bones[i].animations[0].createRange(name, from, to);
  71852. }
  71853. }
  71854. }
  71855. };
  71856. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  71857. if (deleteFrames === void 0) { deleteFrames = true; }
  71858. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  71859. if (this.bones[i].animations[0]) {
  71860. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  71861. }
  71862. }
  71863. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  71864. };
  71865. Skeleton.prototype.getAnimationRange = function (name) {
  71866. return this._ranges[name];
  71867. };
  71868. /**
  71869. * Returns as an Array, all AnimationRanges defined on this skeleton
  71870. */
  71871. Skeleton.prototype.getAnimationRanges = function () {
  71872. var animationRanges = [];
  71873. var name;
  71874. var i = 0;
  71875. for (name in this._ranges) {
  71876. animationRanges[i] = this._ranges[name];
  71877. i++;
  71878. }
  71879. return animationRanges;
  71880. };
  71881. /**
  71882. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  71883. */
  71884. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  71885. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  71886. if (this._ranges[name] || !source.getAnimationRange(name)) {
  71887. return false;
  71888. }
  71889. var ret = true;
  71890. var frameOffset = this._getHighestAnimationFrame() + 1;
  71891. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  71892. var boneDict = {};
  71893. var sourceBones = source.bones;
  71894. var nBones;
  71895. var i;
  71896. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  71897. boneDict[sourceBones[i].name] = sourceBones[i];
  71898. }
  71899. if (this.bones.length !== sourceBones.length) {
  71900. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  71901. ret = false;
  71902. }
  71903. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  71904. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  71905. var boneName = this.bones[i].name;
  71906. var sourceBone = boneDict[boneName];
  71907. if (sourceBone) {
  71908. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  71909. }
  71910. else {
  71911. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  71912. ret = false;
  71913. }
  71914. }
  71915. // do not call createAnimationRange(), since it also is done to bones, which was already done
  71916. var range = source.getAnimationRange(name);
  71917. if (range) {
  71918. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  71919. }
  71920. return ret;
  71921. };
  71922. Skeleton.prototype.returnToRest = function () {
  71923. for (var index = 0; index < this.bones.length; index++) {
  71924. this.bones[index].returnToRest();
  71925. }
  71926. };
  71927. Skeleton.prototype._getHighestAnimationFrame = function () {
  71928. var ret = 0;
  71929. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  71930. if (this.bones[i].animations[0]) {
  71931. var highest = this.bones[i].animations[0].getHighestFrame();
  71932. if (ret < highest) {
  71933. ret = highest;
  71934. }
  71935. }
  71936. }
  71937. return ret;
  71938. };
  71939. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  71940. var range = this.getAnimationRange(name);
  71941. if (!range) {
  71942. return null;
  71943. }
  71944. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  71945. };
  71946. Skeleton.prototype._markAsDirty = function () {
  71947. this._isDirty = true;
  71948. };
  71949. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  71950. this._meshesWithPoseMatrix.push(mesh);
  71951. };
  71952. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  71953. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  71954. if (index > -1) {
  71955. this._meshesWithPoseMatrix.splice(index, 1);
  71956. }
  71957. };
  71958. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  71959. this.onBeforeComputeObservable.notifyObservers(this);
  71960. for (var index = 0; index < this.bones.length; index++) {
  71961. var bone = this.bones[index];
  71962. var parentBone = bone.getParent();
  71963. if (parentBone) {
  71964. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  71965. }
  71966. else {
  71967. if (initialSkinMatrix) {
  71968. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  71969. }
  71970. else {
  71971. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  71972. }
  71973. }
  71974. if (bone._index !== -1) {
  71975. var mappedIndex = bone._index === null ? index : bone._index;
  71976. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  71977. }
  71978. }
  71979. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  71980. };
  71981. Skeleton.prototype.prepare = function () {
  71982. if (!this._isDirty) {
  71983. return;
  71984. }
  71985. if (this.needInitialSkinMatrix) {
  71986. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  71987. var mesh = this._meshesWithPoseMatrix[index];
  71988. var poseMatrix = mesh.getPoseMatrix();
  71989. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  71990. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  71991. }
  71992. if (this._synchronizedWithMesh !== mesh) {
  71993. this._synchronizedWithMesh = mesh;
  71994. // Prepare bones
  71995. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  71996. var bone = this.bones[boneIndex];
  71997. if (!bone.getParent()) {
  71998. var matrix = bone.getBaseMatrix();
  71999. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  72000. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  72001. }
  72002. }
  72003. }
  72004. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  72005. }
  72006. }
  72007. else {
  72008. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  72009. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  72010. }
  72011. this._computeTransformMatrices(this._transformMatrices, null);
  72012. }
  72013. this._isDirty = false;
  72014. this._scene._activeBones.addCount(this.bones.length, false);
  72015. };
  72016. Skeleton.prototype.getAnimatables = function () {
  72017. if (!this._animatables || this._animatables.length !== this.bones.length) {
  72018. this._animatables = [];
  72019. for (var index = 0; index < this.bones.length; index++) {
  72020. this._animatables.push(this.bones[index]);
  72021. }
  72022. }
  72023. return this._animatables;
  72024. };
  72025. Skeleton.prototype.clone = function (name, id) {
  72026. var result = new Skeleton(name, id || name, this._scene);
  72027. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  72028. for (var index = 0; index < this.bones.length; index++) {
  72029. var source = this.bones[index];
  72030. var parentBone = null;
  72031. var parent_1 = source.getParent();
  72032. if (parent_1) {
  72033. var parentIndex = this.bones.indexOf(parent_1);
  72034. parentBone = result.bones[parentIndex];
  72035. }
  72036. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  72037. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  72038. }
  72039. if (this._ranges) {
  72040. result._ranges = {};
  72041. for (var rangeName in this._ranges) {
  72042. var range = this._ranges[rangeName];
  72043. if (range) {
  72044. result._ranges[rangeName] = range.clone();
  72045. }
  72046. }
  72047. }
  72048. this._isDirty = true;
  72049. return result;
  72050. };
  72051. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  72052. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  72053. this.bones.forEach(function (bone) {
  72054. bone.animations.forEach(function (animation) {
  72055. animation.enableBlending = true;
  72056. animation.blendingSpeed = blendingSpeed;
  72057. });
  72058. });
  72059. };
  72060. Skeleton.prototype.dispose = function () {
  72061. this._meshesWithPoseMatrix = [];
  72062. // Animations
  72063. this.getScene().stopAnimation(this);
  72064. // Remove from scene
  72065. this.getScene().removeSkeleton(this);
  72066. };
  72067. Skeleton.prototype.serialize = function () {
  72068. var serializationObject = {};
  72069. serializationObject.name = this.name;
  72070. serializationObject.id = this.id;
  72071. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  72072. serializationObject.bones = [];
  72073. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  72074. for (var index = 0; index < this.bones.length; index++) {
  72075. var bone = this.bones[index];
  72076. var parent_2 = bone.getParent();
  72077. var serializedBone = {
  72078. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  72079. name: bone.name,
  72080. matrix: bone.getBaseMatrix().toArray(),
  72081. rest: bone.getRestPose().toArray()
  72082. };
  72083. serializationObject.bones.push(serializedBone);
  72084. if (bone.length) {
  72085. serializedBone.length = bone.length;
  72086. }
  72087. if (bone.animations && bone.animations.length > 0) {
  72088. serializedBone.animation = bone.animations[0].serialize();
  72089. }
  72090. serializationObject.ranges = [];
  72091. for (var name in this._ranges) {
  72092. var source = this._ranges[name];
  72093. if (!source) {
  72094. continue;
  72095. }
  72096. var range = {};
  72097. range.name = name;
  72098. range.from = source.from;
  72099. range.to = source.to;
  72100. serializationObject.ranges.push(range);
  72101. }
  72102. }
  72103. return serializationObject;
  72104. };
  72105. Skeleton.Parse = function (parsedSkeleton, scene) {
  72106. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  72107. if (parsedSkeleton.dimensionsAtRest) {
  72108. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  72109. }
  72110. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  72111. var index;
  72112. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  72113. var parsedBone = parsedSkeleton.bones[index];
  72114. var parentBone = null;
  72115. if (parsedBone.parentBoneIndex > -1) {
  72116. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  72117. }
  72118. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  72119. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  72120. if (parsedBone.length) {
  72121. bone.length = parsedBone.length;
  72122. }
  72123. if (parsedBone.animation) {
  72124. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  72125. }
  72126. }
  72127. // placed after bones, so createAnimationRange can cascade down
  72128. if (parsedSkeleton.ranges) {
  72129. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  72130. var data = parsedSkeleton.ranges[index];
  72131. skeleton.createAnimationRange(data.name, data.from, data.to);
  72132. }
  72133. }
  72134. return skeleton;
  72135. };
  72136. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  72137. if (forceUpdate === void 0) { forceUpdate = false; }
  72138. var renderId = this._scene.getRenderId();
  72139. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  72140. this.bones[0].computeAbsoluteTransforms();
  72141. this._lastAbsoluteTransformsUpdateId = renderId;
  72142. }
  72143. };
  72144. Skeleton.prototype.getPoseMatrix = function () {
  72145. var poseMatrix = null;
  72146. if (this._meshesWithPoseMatrix.length > 0) {
  72147. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  72148. }
  72149. return poseMatrix;
  72150. };
  72151. Skeleton.prototype.sortBones = function () {
  72152. var bones = new Array();
  72153. var visited = new Array(this.bones.length);
  72154. for (var index = 0; index < this.bones.length; index++) {
  72155. this._sortBones(index, bones, visited);
  72156. }
  72157. this.bones = bones;
  72158. };
  72159. Skeleton.prototype._sortBones = function (index, bones, visited) {
  72160. if (visited[index]) {
  72161. return;
  72162. }
  72163. visited[index] = true;
  72164. var bone = this.bones[index];
  72165. if (bone._index === undefined) {
  72166. bone._index = index;
  72167. }
  72168. var parentBone = bone.getParent();
  72169. if (parentBone) {
  72170. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  72171. }
  72172. bones.push(bone);
  72173. };
  72174. return Skeleton;
  72175. }());
  72176. BABYLON.Skeleton = Skeleton;
  72177. })(BABYLON || (BABYLON = {}));
  72178. //# sourceMappingURL=babylon.skeleton.js.map
  72179. var BABYLON;
  72180. (function (BABYLON) {
  72181. var SphericalPolynomial = /** @class */ (function () {
  72182. function SphericalPolynomial() {
  72183. this.x = BABYLON.Vector3.Zero();
  72184. this.y = BABYLON.Vector3.Zero();
  72185. this.z = BABYLON.Vector3.Zero();
  72186. this.xx = BABYLON.Vector3.Zero();
  72187. this.yy = BABYLON.Vector3.Zero();
  72188. this.zz = BABYLON.Vector3.Zero();
  72189. this.xy = BABYLON.Vector3.Zero();
  72190. this.yz = BABYLON.Vector3.Zero();
  72191. this.zx = BABYLON.Vector3.Zero();
  72192. }
  72193. SphericalPolynomial.prototype.addAmbient = function (color) {
  72194. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  72195. this.xx = this.xx.add(colorVector);
  72196. this.yy = this.yy.add(colorVector);
  72197. this.zz = this.zz.add(colorVector);
  72198. };
  72199. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  72200. var result = new SphericalPolynomial();
  72201. result.x = harmonics.L11.scale(1.02333);
  72202. result.y = harmonics.L1_1.scale(1.02333);
  72203. result.z = harmonics.L10.scale(1.02333);
  72204. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  72205. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  72206. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  72207. result.yz = harmonics.L2_1.scale(0.858086);
  72208. result.zx = harmonics.L21.scale(0.858086);
  72209. result.xy = harmonics.L2_2.scale(0.858086);
  72210. result.scale(1.0 / Math.PI);
  72211. return result;
  72212. };
  72213. SphericalPolynomial.prototype.scale = function (scale) {
  72214. this.x = this.x.scale(scale);
  72215. this.y = this.y.scale(scale);
  72216. this.z = this.z.scale(scale);
  72217. this.xx = this.xx.scale(scale);
  72218. this.yy = this.yy.scale(scale);
  72219. this.zz = this.zz.scale(scale);
  72220. this.yz = this.yz.scale(scale);
  72221. this.zx = this.zx.scale(scale);
  72222. this.xy = this.xy.scale(scale);
  72223. };
  72224. return SphericalPolynomial;
  72225. }());
  72226. BABYLON.SphericalPolynomial = SphericalPolynomial;
  72227. var SphericalHarmonics = /** @class */ (function () {
  72228. function SphericalHarmonics() {
  72229. this.L00 = BABYLON.Vector3.Zero();
  72230. this.L1_1 = BABYLON.Vector3.Zero();
  72231. this.L10 = BABYLON.Vector3.Zero();
  72232. this.L11 = BABYLON.Vector3.Zero();
  72233. this.L2_2 = BABYLON.Vector3.Zero();
  72234. this.L2_1 = BABYLON.Vector3.Zero();
  72235. this.L20 = BABYLON.Vector3.Zero();
  72236. this.L21 = BABYLON.Vector3.Zero();
  72237. this.L22 = BABYLON.Vector3.Zero();
  72238. }
  72239. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  72240. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  72241. var c = colorVector.scale(deltaSolidAngle);
  72242. this.L00 = this.L00.add(c.scale(0.282095));
  72243. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  72244. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  72245. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  72246. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  72247. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  72248. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  72249. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  72250. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  72251. };
  72252. SphericalHarmonics.prototype.scale = function (scale) {
  72253. this.L00 = this.L00.scale(scale);
  72254. this.L1_1 = this.L1_1.scale(scale);
  72255. this.L10 = this.L10.scale(scale);
  72256. this.L11 = this.L11.scale(scale);
  72257. this.L2_2 = this.L2_2.scale(scale);
  72258. this.L2_1 = this.L2_1.scale(scale);
  72259. this.L20 = this.L20.scale(scale);
  72260. this.L21 = this.L21.scale(scale);
  72261. this.L22 = this.L22.scale(scale);
  72262. };
  72263. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  72264. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  72265. //
  72266. // E_lm = A_l * L_lm
  72267. //
  72268. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  72269. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  72270. // the scaling factors are given in equation 9.
  72271. // Constant (Band 0)
  72272. this.L00 = this.L00.scale(3.141593);
  72273. // Linear (Band 1)
  72274. this.L1_1 = this.L1_1.scale(2.094395);
  72275. this.L10 = this.L10.scale(2.094395);
  72276. this.L11 = this.L11.scale(2.094395);
  72277. // Quadratic (Band 2)
  72278. this.L2_2 = this.L2_2.scale(0.785398);
  72279. this.L2_1 = this.L2_1.scale(0.785398);
  72280. this.L20 = this.L20.scale(0.785398);
  72281. this.L21 = this.L21.scale(0.785398);
  72282. this.L22 = this.L22.scale(0.785398);
  72283. };
  72284. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  72285. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  72286. // L = (1/pi) * E * rho
  72287. //
  72288. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  72289. this.scale(1.0 / Math.PI);
  72290. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  72291. // (The pixel shader must apply albedo after texture fetches, etc).
  72292. };
  72293. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  72294. var result = new SphericalHarmonics();
  72295. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  72296. result.L1_1 = polynomial.y.scale(0.977204);
  72297. result.L10 = polynomial.z.scale(0.977204);
  72298. result.L11 = polynomial.x.scale(0.977204);
  72299. result.L2_2 = polynomial.xy.scale(1.16538);
  72300. result.L2_1 = polynomial.yz.scale(1.16538);
  72301. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  72302. result.L21 = polynomial.zx.scale(1.16538);
  72303. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  72304. result.scale(Math.PI);
  72305. return result;
  72306. };
  72307. return SphericalHarmonics;
  72308. }());
  72309. BABYLON.SphericalHarmonics = SphericalHarmonics;
  72310. })(BABYLON || (BABYLON = {}));
  72311. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  72312. var BABYLON;
  72313. (function (BABYLON) {
  72314. var FileFaceOrientation = /** @class */ (function () {
  72315. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  72316. this.name = name;
  72317. this.worldAxisForNormal = worldAxisForNormal;
  72318. this.worldAxisForFileX = worldAxisForFileX;
  72319. this.worldAxisForFileY = worldAxisForFileY;
  72320. }
  72321. return FileFaceOrientation;
  72322. }());
  72323. ;
  72324. /**
  72325. * Helper class dealing with the extraction of spherical polynomial dataArray
  72326. * from a cube map.
  72327. */
  72328. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  72329. function CubeMapToSphericalPolynomialTools() {
  72330. }
  72331. /**
  72332. * Converts a texture to the according Spherical Polynomial data.
  72333. * This extracts the first 3 orders only as they are the only one used in the lighting.
  72334. *
  72335. * @param texture The texture to extract the information from.
  72336. * @return The Spherical Polynomial data.
  72337. */
  72338. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  72339. if (!texture.isCube) {
  72340. // Only supports cube Textures currently.
  72341. return null;
  72342. }
  72343. var size = texture.getSize().width;
  72344. var right = texture.readPixels(0);
  72345. var left = texture.readPixels(1);
  72346. var up;
  72347. var down;
  72348. if (texture.isRenderTarget) {
  72349. up = texture.readPixels(3);
  72350. down = texture.readPixels(2);
  72351. }
  72352. else {
  72353. up = texture.readPixels(2);
  72354. down = texture.readPixels(3);
  72355. }
  72356. var front = texture.readPixels(4);
  72357. var back = texture.readPixels(5);
  72358. var gammaSpace = texture.gammaSpace;
  72359. // Always read as RGBA.
  72360. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  72361. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  72362. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  72363. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  72364. }
  72365. var cubeInfo = {
  72366. size: size,
  72367. right: right,
  72368. left: left,
  72369. up: up,
  72370. down: down,
  72371. front: front,
  72372. back: back,
  72373. format: format,
  72374. type: type,
  72375. gammaSpace: gammaSpace,
  72376. };
  72377. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  72378. };
  72379. /**
  72380. * Converts a cubemap to the according Spherical Polynomial data.
  72381. * This extracts the first 3 orders only as they are the only one used in the lighting.
  72382. *
  72383. * @param cubeInfo The Cube map to extract the information from.
  72384. * @return The Spherical Polynomial data.
  72385. */
  72386. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  72387. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  72388. var totalSolidAngle = 0.0;
  72389. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  72390. var du = 2.0 / cubeInfo.size;
  72391. var dv = du;
  72392. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  72393. var minUV = du * 0.5 - 1.0;
  72394. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  72395. var fileFace = this.FileFaces[faceIndex];
  72396. var dataArray = cubeInfo[fileFace.name];
  72397. var v = minUV;
  72398. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  72399. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  72400. // Because SP is still linear, so summation is fine in that basis.
  72401. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  72402. for (var y = 0; y < cubeInfo.size; y++) {
  72403. var u = minUV;
  72404. for (var x = 0; x < cubeInfo.size; x++) {
  72405. // World direction (not normalised)
  72406. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  72407. worldDirection.normalize();
  72408. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  72409. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  72410. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  72411. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  72412. // Handle Integer types.
  72413. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  72414. r /= 255;
  72415. g /= 255;
  72416. b /= 255;
  72417. }
  72418. // Handle Gamma space textures.
  72419. if (cubeInfo.gammaSpace) {
  72420. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  72421. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  72422. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  72423. }
  72424. var color = new BABYLON.Color3(r, g, b);
  72425. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  72426. totalSolidAngle += deltaSolidAngle;
  72427. u += du;
  72428. }
  72429. v += dv;
  72430. }
  72431. }
  72432. // Solid angle for entire sphere is 4*pi
  72433. var sphereSolidAngle = 4.0 * Math.PI;
  72434. // Adjust the solid angle to allow for how many faces we processed.
  72435. var facesProcessed = 6.0;
  72436. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  72437. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  72438. // This is needed because the numerical integration over the cube uses a
  72439. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  72440. // and also to compensate for accumulative error due to float precision in the summation.
  72441. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  72442. sphericalHarmonics.scale(correctionFactor);
  72443. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  72444. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  72445. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  72446. };
  72447. CubeMapToSphericalPolynomialTools.FileFaces = [
  72448. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  72449. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  72450. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  72451. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  72452. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  72453. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  72454. ];
  72455. return CubeMapToSphericalPolynomialTools;
  72456. }());
  72457. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  72458. })(BABYLON || (BABYLON = {}));
  72459. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  72460. var BABYLON;
  72461. (function (BABYLON) {
  72462. /**
  72463. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  72464. */
  72465. var PanoramaToCubeMapTools = /** @class */ (function () {
  72466. function PanoramaToCubeMapTools() {
  72467. }
  72468. /**
  72469. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  72470. *
  72471. * @param float32Array The source data.
  72472. * @param inputWidth The width of the input panorama.
  72473. * @param inputhHeight The height of the input panorama.
  72474. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  72475. * @return The cubemap data
  72476. */
  72477. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  72478. if (!float32Array) {
  72479. throw "ConvertPanoramaToCubemap: input cannot be null";
  72480. }
  72481. if (float32Array.length != inputWidth * inputHeight * 3) {
  72482. throw "ConvertPanoramaToCubemap: input size is wrong";
  72483. }
  72484. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  72485. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  72486. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  72487. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  72488. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  72489. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  72490. return {
  72491. front: textureFront,
  72492. back: textureBack,
  72493. left: textureLeft,
  72494. right: textureRight,
  72495. up: textureUp,
  72496. down: textureDown,
  72497. size: size,
  72498. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  72499. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  72500. gammaSpace: false,
  72501. };
  72502. };
  72503. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  72504. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  72505. var textureArray = new Float32Array(buffer);
  72506. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  72507. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  72508. var dy = 1 / texSize;
  72509. var fy = 0;
  72510. for (var y = 0; y < texSize; y++) {
  72511. var xv1 = faceData[0];
  72512. var xv2 = faceData[2];
  72513. for (var x = 0; x < texSize; x++) {
  72514. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  72515. v.normalize();
  72516. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  72517. // 3 channels per pixels
  72518. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  72519. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  72520. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  72521. xv1 = xv1.add(rotDX1);
  72522. xv2 = xv2.add(rotDX2);
  72523. }
  72524. fy += dy;
  72525. }
  72526. return textureArray;
  72527. };
  72528. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  72529. var theta = Math.atan2(vDir.z, vDir.x);
  72530. var phi = Math.acos(vDir.y);
  72531. while (theta < -Math.PI)
  72532. theta += 2 * Math.PI;
  72533. while (theta > Math.PI)
  72534. theta -= 2 * Math.PI;
  72535. var dx = theta / Math.PI;
  72536. var dy = phi / Math.PI;
  72537. // recenter.
  72538. dx = dx * 0.5 + 0.5;
  72539. var px = Math.round(dx * inputWidth);
  72540. if (px < 0)
  72541. px = 0;
  72542. else if (px >= inputWidth)
  72543. px = inputWidth - 1;
  72544. var py = Math.round(dy * inputHeight);
  72545. if (py < 0)
  72546. py = 0;
  72547. else if (py >= inputHeight)
  72548. py = inputHeight - 1;
  72549. var inputY = (inputHeight - py - 1);
  72550. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  72551. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  72552. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  72553. return {
  72554. r: r,
  72555. g: g,
  72556. b: b
  72557. };
  72558. };
  72559. PanoramaToCubeMapTools.FACE_FRONT = [
  72560. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72561. new BABYLON.Vector3(1.0, -1.0, -1.0),
  72562. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  72563. new BABYLON.Vector3(1.0, 1.0, -1.0)
  72564. ];
  72565. PanoramaToCubeMapTools.FACE_BACK = [
  72566. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72567. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72568. new BABYLON.Vector3(1.0, 1.0, 1.0),
  72569. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  72570. ];
  72571. PanoramaToCubeMapTools.FACE_RIGHT = [
  72572. new BABYLON.Vector3(1.0, -1.0, -1.0),
  72573. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72574. new BABYLON.Vector3(1.0, 1.0, -1.0),
  72575. new BABYLON.Vector3(1.0, 1.0, 1.0)
  72576. ];
  72577. PanoramaToCubeMapTools.FACE_LEFT = [
  72578. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72579. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72580. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  72581. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  72582. ];
  72583. PanoramaToCubeMapTools.FACE_DOWN = [
  72584. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  72585. new BABYLON.Vector3(1.0, 1.0, -1.0),
  72586. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  72587. new BABYLON.Vector3(1.0, 1.0, 1.0)
  72588. ];
  72589. PanoramaToCubeMapTools.FACE_UP = [
  72590. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72591. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72592. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72593. new BABYLON.Vector3(1.0, -1.0, -1.0)
  72594. ];
  72595. return PanoramaToCubeMapTools;
  72596. }());
  72597. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  72598. })(BABYLON || (BABYLON = {}));
  72599. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  72600. var BABYLON;
  72601. (function (BABYLON) {
  72602. ;
  72603. /**
  72604. * This groups tools to convert HDR texture to native colors array.
  72605. */
  72606. var HDRTools = /** @class */ (function () {
  72607. function HDRTools() {
  72608. }
  72609. HDRTools.Ldexp = function (mantissa, exponent) {
  72610. if (exponent > 1023) {
  72611. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  72612. }
  72613. if (exponent < -1074) {
  72614. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  72615. }
  72616. return mantissa * Math.pow(2, exponent);
  72617. };
  72618. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  72619. if (exponent > 0) {
  72620. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  72621. float32array[index + 0] = red * exponent;
  72622. float32array[index + 1] = green * exponent;
  72623. float32array[index + 2] = blue * exponent;
  72624. }
  72625. else {
  72626. float32array[index + 0] = 0;
  72627. float32array[index + 1] = 0;
  72628. float32array[index + 2] = 0;
  72629. }
  72630. };
  72631. HDRTools.readStringLine = function (uint8array, startIndex) {
  72632. var line = "";
  72633. var character = "";
  72634. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  72635. character = String.fromCharCode(uint8array[i]);
  72636. if (character == "\n") {
  72637. break;
  72638. }
  72639. line += character;
  72640. }
  72641. return line;
  72642. };
  72643. /**
  72644. * Reads header information from an RGBE texture stored in a native array.
  72645. * More information on this format are available here:
  72646. * https://en.wikipedia.org/wiki/RGBE_image_format
  72647. *
  72648. * @param uint8array The binary file stored in native array.
  72649. * @return The header information.
  72650. */
  72651. HDRTools.RGBE_ReadHeader = function (uint8array) {
  72652. var height = 0;
  72653. var width = 0;
  72654. var line = this.readStringLine(uint8array, 0);
  72655. if (line[0] != '#' || line[1] != '?') {
  72656. throw "Bad HDR Format.";
  72657. }
  72658. var endOfHeader = false;
  72659. var findFormat = false;
  72660. var lineIndex = 0;
  72661. do {
  72662. lineIndex += (line.length + 1);
  72663. line = this.readStringLine(uint8array, lineIndex);
  72664. if (line == "FORMAT=32-bit_rle_rgbe") {
  72665. findFormat = true;
  72666. }
  72667. else if (line.length == 0) {
  72668. endOfHeader = true;
  72669. }
  72670. } while (!endOfHeader);
  72671. if (!findFormat) {
  72672. throw "HDR Bad header format, unsupported FORMAT";
  72673. }
  72674. lineIndex += (line.length + 1);
  72675. line = this.readStringLine(uint8array, lineIndex);
  72676. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  72677. var match = sizeRegexp.exec(line);
  72678. // TODO. Support +Y and -X if needed.
  72679. if (!match || match.length < 3) {
  72680. throw "HDR Bad header format, no size";
  72681. }
  72682. width = parseInt(match[2]);
  72683. height = parseInt(match[1]);
  72684. if (width < 8 || width > 0x7fff) {
  72685. throw "HDR Bad header format, unsupported size";
  72686. }
  72687. lineIndex += (line.length + 1);
  72688. return {
  72689. height: height,
  72690. width: width,
  72691. dataPosition: lineIndex
  72692. };
  72693. };
  72694. /**
  72695. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  72696. * This RGBE texture needs to store the information as a panorama.
  72697. *
  72698. * More information on this format are available here:
  72699. * https://en.wikipedia.org/wiki/RGBE_image_format
  72700. *
  72701. * @param buffer The binary file stored in an array buffer.
  72702. * @param size The expected size of the extracted cubemap.
  72703. * @return The Cube Map information.
  72704. */
  72705. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  72706. var uint8array = new Uint8Array(buffer);
  72707. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  72708. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  72709. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  72710. return cubeMapData;
  72711. };
  72712. /**
  72713. * Returns the pixels data extracted from an RGBE texture.
  72714. * This pixels will be stored left to right up to down in the R G B order in one array.
  72715. *
  72716. * More information on this format are available here:
  72717. * https://en.wikipedia.org/wiki/RGBE_image_format
  72718. *
  72719. * @param uint8array The binary file stored in an array buffer.
  72720. * @param hdrInfo The header information of the file.
  72721. * @return The pixels data in RGB right to left up to down order.
  72722. */
  72723. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  72724. // Keep for multi format supports.
  72725. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  72726. };
  72727. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  72728. var num_scanlines = hdrInfo.height;
  72729. var scanline_width = hdrInfo.width;
  72730. var a, b, c, d, count;
  72731. var dataIndex = hdrInfo.dataPosition;
  72732. var index = 0, endIndex = 0, i = 0;
  72733. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  72734. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  72735. // 3 channels of 4 bytes per pixel in float.
  72736. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  72737. var resultArray = new Float32Array(resultBuffer);
  72738. // read in each successive scanline
  72739. while (num_scanlines > 0) {
  72740. a = uint8array[dataIndex++];
  72741. b = uint8array[dataIndex++];
  72742. c = uint8array[dataIndex++];
  72743. d = uint8array[dataIndex++];
  72744. if (a != 2 || b != 2 || (c & 0x80)) {
  72745. // this file is not run length encoded
  72746. throw "HDR Bad header format, not RLE";
  72747. }
  72748. if (((c << 8) | d) != scanline_width) {
  72749. throw "HDR Bad header format, wrong scan line width";
  72750. }
  72751. index = 0;
  72752. // read each of the four channels for the scanline into the buffer
  72753. for (i = 0; i < 4; i++) {
  72754. endIndex = (i + 1) * scanline_width;
  72755. while (index < endIndex) {
  72756. a = uint8array[dataIndex++];
  72757. b = uint8array[dataIndex++];
  72758. if (a > 128) {
  72759. // a run of the same value
  72760. count = a - 128;
  72761. if ((count == 0) || (count > endIndex - index)) {
  72762. throw "HDR Bad Format, bad scanline data (run)";
  72763. }
  72764. while (count-- > 0) {
  72765. scanLineArray[index++] = b;
  72766. }
  72767. }
  72768. else {
  72769. // a non-run
  72770. count = a;
  72771. if ((count == 0) || (count > endIndex - index)) {
  72772. throw "HDR Bad Format, bad scanline data (non-run)";
  72773. }
  72774. scanLineArray[index++] = b;
  72775. if (--count > 0) {
  72776. for (var j = 0; j < count; j++) {
  72777. scanLineArray[index++] = uint8array[dataIndex++];
  72778. }
  72779. }
  72780. }
  72781. }
  72782. }
  72783. // now convert data from buffer into floats
  72784. for (i = 0; i < scanline_width; i++) {
  72785. a = scanLineArray[i];
  72786. b = scanLineArray[i + scanline_width];
  72787. c = scanLineArray[i + 2 * scanline_width];
  72788. d = scanLineArray[i + 3 * scanline_width];
  72789. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  72790. }
  72791. num_scanlines--;
  72792. }
  72793. return resultArray;
  72794. };
  72795. return HDRTools;
  72796. }());
  72797. BABYLON.HDRTools = HDRTools;
  72798. })(BABYLON || (BABYLON = {}));
  72799. //# sourceMappingURL=babylon.hdr.js.map
  72800. var BABYLON;
  72801. (function (BABYLON) {
  72802. /**
  72803. * This represents a texture coming from an HDR input.
  72804. *
  72805. * The only supported format is currently panorama picture stored in RGBE format.
  72806. * Example of such files can be found on HDRLib: http://hdrlib.com/
  72807. */
  72808. var HDRCubeTexture = /** @class */ (function (_super) {
  72809. __extends(HDRCubeTexture, _super);
  72810. /**
  72811. * Instantiates an HDRTexture from the following parameters.
  72812. *
  72813. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  72814. * @param scene The scene the texture will be used in
  72815. * @param size The cubemap 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.
  72816. * @param noMipmap Forces to not generate the mipmap if true
  72817. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  72818. * @param useInGammaSpace 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)
  72819. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  72820. */
  72821. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  72822. if (noMipmap === void 0) { noMipmap = false; }
  72823. if (generateHarmonics === void 0) { generateHarmonics = true; }
  72824. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  72825. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  72826. if (onLoad === void 0) { onLoad = null; }
  72827. if (onError === void 0) { onError = null; }
  72828. var _this = _super.call(this, scene) || this;
  72829. _this._useInGammaSpace = false;
  72830. _this._generateHarmonics = true;
  72831. _this._isBABYLONPreprocessed = false;
  72832. _this._onLoad = null;
  72833. _this._onError = null;
  72834. /**
  72835. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  72836. */
  72837. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  72838. /**
  72839. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  72840. * This is usefull at run time to apply the good shader.
  72841. */
  72842. _this.isPMREM = false;
  72843. _this._isBlocking = true;
  72844. /**
  72845. * Gets or sets the center of the bounding box associated with the cube texture
  72846. * It must define where the camera used to render the texture was set
  72847. */
  72848. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  72849. if (!url) {
  72850. return _this;
  72851. }
  72852. _this.name = url;
  72853. _this.url = url;
  72854. _this.hasAlpha = false;
  72855. _this.isCube = true;
  72856. _this._textureMatrix = BABYLON.Matrix.Identity();
  72857. _this._onLoad = onLoad;
  72858. _this._onError = onError;
  72859. _this.gammaSpace = false;
  72860. var caps = scene.getEngine().getCaps();
  72861. if (size) {
  72862. _this._isBABYLONPreprocessed = false;
  72863. _this._noMipmap = noMipmap;
  72864. _this._size = size;
  72865. _this._useInGammaSpace = useInGammaSpace;
  72866. _this._usePMREMGenerator = usePMREMGenerator &&
  72867. caps.textureLOD &&
  72868. caps.textureFloat &&
  72869. !_this._useInGammaSpace;
  72870. }
  72871. else {
  72872. _this._isBABYLONPreprocessed = true;
  72873. _this._noMipmap = false;
  72874. _this._useInGammaSpace = false;
  72875. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  72876. !_this._useInGammaSpace;
  72877. }
  72878. _this.isPMREM = _this._usePMREMGenerator;
  72879. _this._texture = _this._getFromCache(url, _this._noMipmap);
  72880. if (!_this._texture) {
  72881. if (!scene.useDelayedTextureLoading) {
  72882. _this.loadTexture();
  72883. }
  72884. else {
  72885. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  72886. }
  72887. }
  72888. return _this;
  72889. }
  72890. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  72891. /**
  72892. * Gets wether or not the texture is blocking during loading.
  72893. */
  72894. get: function () {
  72895. return this._isBlocking;
  72896. },
  72897. /**
  72898. * Sets wether or not the texture is blocking during loading.
  72899. */
  72900. set: function (value) {
  72901. this._isBlocking = value;
  72902. },
  72903. enumerable: true,
  72904. configurable: true
  72905. });
  72906. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  72907. get: function () {
  72908. return this._boundingBoxSize;
  72909. },
  72910. /**
  72911. * Gets or sets the size of the bounding box associated with the cube texture
  72912. * When defined, the cubemap will switch to local mode
  72913. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  72914. * @example https://www.babylonjs-playground.com/#RNASML
  72915. */
  72916. set: function (value) {
  72917. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  72918. return;
  72919. }
  72920. this._boundingBoxSize = value;
  72921. var scene = this.getScene();
  72922. if (scene) {
  72923. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  72924. }
  72925. },
  72926. enumerable: true,
  72927. configurable: true
  72928. });
  72929. /**
  72930. * Occurs when the file is a preprocessed .babylon.hdr file.
  72931. */
  72932. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  72933. var _this = this;
  72934. var mipLevels = 0;
  72935. var floatArrayView = null;
  72936. var scene = this.getScene();
  72937. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  72938. var mips = new Array();
  72939. if (!floatArrayView) {
  72940. return mips;
  72941. }
  72942. var startIndex = 30;
  72943. for (var level = 0; level < mipLevels; level++) {
  72944. mips.push([]);
  72945. // Fill each pixel of the mip level.
  72946. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  72947. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  72948. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  72949. mips[level].push(faceData);
  72950. startIndex += faceSize;
  72951. }
  72952. }
  72953. return mips;
  72954. } : null;
  72955. var callback = function (buffer) {
  72956. var scene = _this.getScene();
  72957. if (!scene) {
  72958. return null;
  72959. }
  72960. // Create Native Array Views
  72961. var intArrayView = new Int32Array(buffer);
  72962. floatArrayView = new Float32Array(buffer);
  72963. // Fill header.
  72964. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  72965. _this._size = intArrayView[1]; // CubeMap max mip face size.
  72966. // Update Texture Information.
  72967. if (!_this._texture) {
  72968. return null;
  72969. }
  72970. _this._texture.updateSize(_this._size, _this._size);
  72971. // Fill polynomial information.
  72972. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  72973. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  72974. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  72975. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  72976. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  72977. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  72978. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  72979. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  72980. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  72981. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  72982. _this.sphericalPolynomial = sphericalPolynomial;
  72983. // Fill pixel data.
  72984. mipLevels = intArrayView[29]; // Number of mip levels.
  72985. var startIndex = 30;
  72986. var data = [];
  72987. var faceSize = Math.pow(_this._size, 2) * 3;
  72988. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  72989. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  72990. startIndex += faceSize;
  72991. }
  72992. var results = [];
  72993. var byteArray = null;
  72994. // Push each faces.
  72995. for (var k = 0; k < 6; k++) {
  72996. var dataFace = null;
  72997. // To be deprecated.
  72998. if (version === 1) {
  72999. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  73000. dataFace = data[j];
  73001. }
  73002. // If special cases.
  73003. if (!mipmapGenerator && dataFace) {
  73004. if (!scene.getEngine().getCaps().textureFloat) {
  73005. // 3 channels of 1 bytes per pixel in bytes.
  73006. var byteBuffer = new ArrayBuffer(faceSize);
  73007. byteArray = new Uint8Array(byteBuffer);
  73008. }
  73009. for (var i = 0; i < _this._size * _this._size; i++) {
  73010. // Put in gamma space if requested.
  73011. if (_this._useInGammaSpace) {
  73012. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  73013. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  73014. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  73015. }
  73016. // Convert to int texture for fallback.
  73017. if (byteArray) {
  73018. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  73019. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  73020. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  73021. // May use luminance instead if the result is not accurate.
  73022. var max = Math.max(Math.max(r, g), b);
  73023. if (max > 255) {
  73024. var scale = 255 / max;
  73025. r *= scale;
  73026. g *= scale;
  73027. b *= scale;
  73028. }
  73029. byteArray[(i * 3) + 0] = r;
  73030. byteArray[(i * 3) + 1] = g;
  73031. byteArray[(i * 3) + 2] = b;
  73032. }
  73033. }
  73034. }
  73035. // Fill the array accordingly.
  73036. if (byteArray) {
  73037. results.push(byteArray);
  73038. }
  73039. else {
  73040. results.push(dataFace);
  73041. }
  73042. }
  73043. return results;
  73044. };
  73045. if (scene) {
  73046. 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, mipmapGenerator, this._onLoad, this._onError);
  73047. }
  73048. };
  73049. /**
  73050. * Occurs when the file is raw .hdr file.
  73051. */
  73052. HDRCubeTexture.prototype.loadHDRTexture = function () {
  73053. var _this = this;
  73054. var callback = function (buffer) {
  73055. var scene = _this.getScene();
  73056. if (!scene) {
  73057. return null;
  73058. }
  73059. // Extract the raw linear data.
  73060. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  73061. // Generate harmonics if needed.
  73062. if (_this._generateHarmonics) {
  73063. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  73064. _this.sphericalPolynomial = sphericalPolynomial;
  73065. }
  73066. var results = [];
  73067. var byteArray = null;
  73068. // Push each faces.
  73069. for (var j = 0; j < 6; j++) {
  73070. // Create uintarray fallback.
  73071. if (!scene.getEngine().getCaps().textureFloat) {
  73072. // 3 channels of 1 bytes per pixel in bytes.
  73073. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  73074. byteArray = new Uint8Array(byteBuffer);
  73075. }
  73076. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  73077. // If special cases.
  73078. if (_this._useInGammaSpace || byteArray) {
  73079. for (var i = 0; i < _this._size * _this._size; i++) {
  73080. // Put in gamma space if requested.
  73081. if (_this._useInGammaSpace) {
  73082. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  73083. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  73084. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  73085. }
  73086. // Convert to int texture for fallback.
  73087. if (byteArray) {
  73088. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  73089. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  73090. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  73091. // May use luminance instead if the result is not accurate.
  73092. var max = Math.max(Math.max(r, g), b);
  73093. if (max > 255) {
  73094. var scale = 255 / max;
  73095. r *= scale;
  73096. g *= scale;
  73097. b *= scale;
  73098. }
  73099. byteArray[(i * 3) + 0] = r;
  73100. byteArray[(i * 3) + 1] = g;
  73101. byteArray[(i * 3) + 2] = b;
  73102. }
  73103. }
  73104. }
  73105. if (byteArray) {
  73106. results.push(byteArray);
  73107. }
  73108. else {
  73109. results.push(dataFace);
  73110. }
  73111. }
  73112. return results;
  73113. };
  73114. var mipmapGenerator = null;
  73115. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  73116. // if (!this._noMipmap &&
  73117. // this._usePMREMGenerator) {
  73118. // mipmapGenerator = (data: ArrayBufferView[]) => {
  73119. // // Custom setup of the generator matching with the PBR shader values.
  73120. // var generator = new BABYLON.PMREMGenerator(data,
  73121. // this._size,
  73122. // this._size,
  73123. // 0,
  73124. // 3,
  73125. // this.getScene().getEngine().getCaps().textureFloat,
  73126. // 2048,
  73127. // 0.25,
  73128. // false,
  73129. // true);
  73130. // return generator.filterCubeMap();
  73131. // };
  73132. // }
  73133. var scene = this.getScene();
  73134. if (scene) {
  73135. 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, mipmapGenerator, this._onLoad, this._onError);
  73136. }
  73137. };
  73138. /**
  73139. * Starts the loading process of the texture.
  73140. */
  73141. HDRCubeTexture.prototype.loadTexture = function () {
  73142. if (this._isBABYLONPreprocessed) {
  73143. this.loadBabylonTexture();
  73144. }
  73145. else {
  73146. this.loadHDRTexture();
  73147. }
  73148. };
  73149. HDRCubeTexture.prototype.clone = function () {
  73150. var scene = this.getScene();
  73151. if (!scene) {
  73152. return this;
  73153. }
  73154. var size = (this._isBABYLONPreprocessed ? null : this._size);
  73155. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  73156. // Base texture
  73157. newTexture.level = this.level;
  73158. newTexture.wrapU = this.wrapU;
  73159. newTexture.wrapV = this.wrapV;
  73160. newTexture.coordinatesIndex = this.coordinatesIndex;
  73161. newTexture.coordinatesMode = this.coordinatesMode;
  73162. return newTexture;
  73163. };
  73164. // Methods
  73165. HDRCubeTexture.prototype.delayLoad = function () {
  73166. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  73167. return;
  73168. }
  73169. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  73170. this._texture = this._getFromCache(this.url, this._noMipmap);
  73171. if (!this._texture) {
  73172. this.loadTexture();
  73173. }
  73174. };
  73175. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  73176. return this._textureMatrix;
  73177. };
  73178. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  73179. this._textureMatrix = value;
  73180. };
  73181. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  73182. var texture = null;
  73183. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  73184. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  73185. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  73186. texture.name = parsedTexture.name;
  73187. texture.hasAlpha = parsedTexture.hasAlpha;
  73188. texture.level = parsedTexture.level;
  73189. texture.coordinatesMode = parsedTexture.coordinatesMode;
  73190. texture.isBlocking = parsedTexture.isBlocking;
  73191. }
  73192. if (texture) {
  73193. if (parsedTexture.boundingBoxPosition) {
  73194. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  73195. }
  73196. if (parsedTexture.boundingBoxSize) {
  73197. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  73198. }
  73199. }
  73200. return texture;
  73201. };
  73202. HDRCubeTexture.prototype.serialize = function () {
  73203. if (!this.name) {
  73204. return null;
  73205. }
  73206. var serializationObject = {};
  73207. serializationObject.name = this.name;
  73208. serializationObject.hasAlpha = this.hasAlpha;
  73209. serializationObject.isCube = true;
  73210. serializationObject.level = this.level;
  73211. serializationObject.size = this._size;
  73212. serializationObject.coordinatesMode = this.coordinatesMode;
  73213. serializationObject.useInGammaSpace = this._useInGammaSpace;
  73214. serializationObject.generateHarmonics = this._generateHarmonics;
  73215. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  73216. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  73217. serializationObject.customType = "BABYLON.HDRCubeTexture";
  73218. serializationObject.noMipmap = this._noMipmap;
  73219. serializationObject.isBlocking = this._isBlocking;
  73220. return serializationObject;
  73221. };
  73222. /**
  73223. * Saves as a file the data contained in the texture in a binary format.
  73224. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  73225. * as the spherical used in the lighting.
  73226. * @param url The HDR file url.
  73227. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  73228. * @param onError Method called if any error happens during download.
  73229. * @return The packed binary data.
  73230. */
  73231. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  73232. if (onError === void 0) { onError = null; }
  73233. var callback = function (buffer) {
  73234. var data = new Blob([buffer], { type: 'application/octet-stream' });
  73235. // Returns a URL you can use as a href.
  73236. var objUrl = window.URL.createObjectURL(data);
  73237. // Simulates a link to it and click to dowload.
  73238. var a = document.createElement("a");
  73239. document.body.appendChild(a);
  73240. a.style.display = "none";
  73241. a.href = objUrl;
  73242. a.download = "envmap.babylon.hdr";
  73243. a.click();
  73244. };
  73245. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  73246. };
  73247. /**
  73248. * Serializes the data contained in the texture in a binary format.
  73249. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  73250. * as the spherical used in the lighting.
  73251. * @param url The HDR file url.
  73252. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  73253. * @param onError Method called if any error happens during download.
  73254. * @return The packed binary data.
  73255. */
  73256. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  73257. if (onError === void 0) { onError = null; }
  73258. // Needs the url tho create the texture.
  73259. if (!url) {
  73260. return;
  73261. }
  73262. // Check Power of two size.
  73263. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  73264. return;
  73265. }
  73266. // Coming Back in 3.x.
  73267. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  73268. };
  73269. HDRCubeTexture._facesMapping = [
  73270. "right",
  73271. "left",
  73272. "up",
  73273. "down",
  73274. "front",
  73275. "back"
  73276. ];
  73277. return HDRCubeTexture;
  73278. }(BABYLON.BaseTexture));
  73279. BABYLON.HDRCubeTexture = HDRCubeTexture;
  73280. })(BABYLON || (BABYLON = {}));
  73281. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  73282. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  73283. // Huge respect for a such great lib.
  73284. // Earcut license:
  73285. // Copyright (c) 2016, Mapbox
  73286. //
  73287. // Permission to use, copy, modify, and/or distribute this software for any purpose
  73288. // with or without fee is hereby granted, provided that the above copyright notice
  73289. // and this permission notice appear in all copies.
  73290. //
  73291. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  73292. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  73293. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  73294. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  73295. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  73296. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  73297. // THIS SOFTWARE.
  73298. var Earcut;
  73299. (function (Earcut) {
  73300. /**
  73301. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  73302. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  73303. * @param holeIndices is an array of hole indices if any (e.g. [5, 8] for a 12- vertice input would mean one hole with vertices 5–7 and another with 8–11).
  73304. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  73305. */
  73306. function earcut(data, holeIndices, dim) {
  73307. dim = dim || 2;
  73308. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  73309. if (!outerNode)
  73310. return triangles;
  73311. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  73312. if (hasHoles)
  73313. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  73314. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  73315. if (data.length > 80 * dim) {
  73316. minX = maxX = data[0];
  73317. minY = maxY = data[1];
  73318. for (var i = dim; i < outerLen; i += dim) {
  73319. x = data[i];
  73320. y = data[i + 1];
  73321. if (x < minX)
  73322. minX = x;
  73323. if (y < minY)
  73324. minY = y;
  73325. if (x > maxX)
  73326. maxX = x;
  73327. if (y > maxY)
  73328. maxY = y;
  73329. }
  73330. // minX, minY and size are later used to transform coords into integers for z-order calculation
  73331. size = Math.max(maxX - minX, maxY - minY);
  73332. }
  73333. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  73334. return triangles;
  73335. }
  73336. Earcut.earcut = earcut;
  73337. var Node = /** @class */ (function () {
  73338. function Node(i, x, y) {
  73339. this.i = i;
  73340. this.x = x;
  73341. this.y = y;
  73342. this.prev = null;
  73343. this.next = null;
  73344. this.z = null;
  73345. this.prevZ = null;
  73346. this.nextZ = null;
  73347. this.steiner = false;
  73348. }
  73349. return Node;
  73350. }());
  73351. // create a circular doubly linked list from polygon points in the specified winding order
  73352. function linkedList(data, start, end, dim, clockwise) {
  73353. var i, last = null;
  73354. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  73355. for (i = start; i < end; i += dim)
  73356. last = insertNode(i, data[i], data[i + 1], last);
  73357. }
  73358. else {
  73359. for (i = end - dim; i >= start; i -= dim)
  73360. last = insertNode(i, data[i], data[i + 1], last);
  73361. }
  73362. if (last && equals(last, last.next)) {
  73363. removeNode(last);
  73364. last = last.next;
  73365. }
  73366. return last;
  73367. }
  73368. // eliminate colinear or duplicate points
  73369. function filterPoints(start, end) {
  73370. if (!start)
  73371. return start;
  73372. if (!end)
  73373. end = start;
  73374. var p = start, again;
  73375. do {
  73376. again = false;
  73377. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  73378. removeNode(p);
  73379. p = end = p.prev;
  73380. if (p === p.next)
  73381. return undefined;
  73382. again = true;
  73383. }
  73384. else {
  73385. p = p.next;
  73386. }
  73387. } while (again || p !== end);
  73388. return end;
  73389. }
  73390. // main ear slicing loop which triangulates a polygon (given as a linked list)
  73391. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  73392. if (!ear)
  73393. return;
  73394. // interlink polygon nodes in z-order
  73395. if (!pass && size)
  73396. indexCurve(ear, minX, minY, size);
  73397. var stop = ear, prev, next;
  73398. // iterate through ears, slicing them one by one
  73399. while (ear.prev !== ear.next) {
  73400. prev = ear.prev;
  73401. next = ear.next;
  73402. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  73403. // cut off the triangle
  73404. triangles.push(prev.i / dim);
  73405. triangles.push(ear.i / dim);
  73406. triangles.push(next.i / dim);
  73407. removeNode(ear);
  73408. // skipping the next vertice leads to less sliver triangles
  73409. ear = next.next;
  73410. stop = next.next;
  73411. continue;
  73412. }
  73413. ear = next;
  73414. // if we looped through the whole remaining polygon and can't find any more ears
  73415. if (ear === stop) {
  73416. // try filtering points and slicing again
  73417. if (!pass) {
  73418. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  73419. // if this didn't work, try curing all small self-intersections locally
  73420. }
  73421. else if (pass === 1) {
  73422. ear = cureLocalIntersections(ear, triangles, dim);
  73423. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  73424. // as a last resort, try splitting the remaining polygon into two
  73425. }
  73426. else if (pass === 2) {
  73427. splitEarcut(ear, triangles, dim, minX, minY, size);
  73428. }
  73429. break;
  73430. }
  73431. }
  73432. }
  73433. // check whether a polygon node forms a valid ear with adjacent nodes
  73434. function isEar(ear) {
  73435. var a = ear.prev, b = ear, c = ear.next;
  73436. if (area(a, b, c) >= 0)
  73437. return false; // reflex, can't be an ear
  73438. // now make sure we don't have other points inside the potential ear
  73439. var p = ear.next.next;
  73440. while (p !== ear.prev) {
  73441. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  73442. area(p.prev, p, p.next) >= 0)
  73443. return false;
  73444. p = p.next;
  73445. }
  73446. return true;
  73447. }
  73448. function isEarHashed(ear, minX, minY, size) {
  73449. var a = ear.prev, b = ear, c = ear.next;
  73450. if (area(a, b, c) >= 0)
  73451. return false; // reflex, can't be an ear
  73452. // triangle bbox; min & max are calculated like this for speed
  73453. var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
  73454. // z-order range for the current triangle bbox;
  73455. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  73456. // first look for points inside the triangle in increasing z-order
  73457. var p = ear.nextZ;
  73458. while (p && p.z <= maxZ) {
  73459. if (p !== ear.prev &&
  73460. p !== ear.next &&
  73461. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  73462. area(p.prev, p, p.next) >= 0)
  73463. return false;
  73464. p = p.nextZ;
  73465. }
  73466. // then look for points in decreasing z-order
  73467. p = ear.prevZ;
  73468. while (p && p.z >= minZ) {
  73469. if (p !== ear.prev &&
  73470. p !== ear.next &&
  73471. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  73472. area(p.prev, p, p.next) >= 0)
  73473. return false;
  73474. p = p.prevZ;
  73475. }
  73476. return true;
  73477. }
  73478. // go through all polygon nodes and cure small local self-intersections
  73479. function cureLocalIntersections(start, triangles, dim) {
  73480. var p = start;
  73481. do {
  73482. var a = p.prev, b = p.next.next;
  73483. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  73484. triangles.push(a.i / dim);
  73485. triangles.push(p.i / dim);
  73486. triangles.push(b.i / dim);
  73487. // remove two nodes involved
  73488. removeNode(p);
  73489. removeNode(p.next);
  73490. p = start = b;
  73491. }
  73492. p = p.next;
  73493. } while (p !== start);
  73494. return p;
  73495. }
  73496. // try splitting polygon into two and triangulate them independently
  73497. function splitEarcut(start, triangles, dim, minX, minY, size) {
  73498. // look for a valid diagonal that divides the polygon into two
  73499. var a = start;
  73500. do {
  73501. var b = a.next.next;
  73502. while (b !== a.prev) {
  73503. if (a.i !== b.i && isValidDiagonal(a, b)) {
  73504. // split the polygon in two by the diagonal
  73505. var c = splitPolygon(a, b);
  73506. // filter colinear points around the cuts
  73507. a = filterPoints(a, a.next);
  73508. c = filterPoints(c, c.next);
  73509. // run earcut on each half
  73510. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  73511. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  73512. return;
  73513. }
  73514. b = b.next;
  73515. }
  73516. a = a.next;
  73517. } while (a !== start);
  73518. }
  73519. // link every hole into the outer loop, producing a single-ring polygon without holes
  73520. function eliminateHoles(data, holeIndices, outerNode, dim) {
  73521. var queue = [], i, len, start, end, list;
  73522. for (i = 0, len = holeIndices.length; i < len; i++) {
  73523. start = holeIndices[i] * dim;
  73524. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  73525. list = linkedList(data, start, end, dim, false);
  73526. if (list === list.next)
  73527. list.steiner = true;
  73528. queue.push(getLeftmost(list));
  73529. }
  73530. queue.sort(compareX);
  73531. // process holes from left to right
  73532. for (i = 0; i < queue.length; i++) {
  73533. eliminateHole(queue[i], outerNode);
  73534. outerNode = filterPoints(outerNode, outerNode.next);
  73535. }
  73536. return outerNode;
  73537. }
  73538. function compareX(a, b) {
  73539. return a.x - b.x;
  73540. }
  73541. // find a bridge between vertices that connects hole with an outer ring and and link it
  73542. function eliminateHole(hole, outerNode) {
  73543. outerNode = findHoleBridge(hole, outerNode);
  73544. if (outerNode) {
  73545. var b = splitPolygon(outerNode, hole);
  73546. filterPoints(b, b.next);
  73547. }
  73548. }
  73549. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  73550. function findHoleBridge(hole, outerNode) {
  73551. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  73552. // find a segment intersected by a ray from the hole's leftmost point to the left;
  73553. // segment's endpoint with lesser x will be potential connection point
  73554. do {
  73555. if (hy <= p.y && hy >= p.next.y) {
  73556. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  73557. if (x <= hx && x > qx) {
  73558. qx = x;
  73559. if (x === hx) {
  73560. if (hy === p.y)
  73561. return p;
  73562. if (hy === p.next.y)
  73563. return p.next;
  73564. }
  73565. m = p.x < p.next.x ? p : p.next;
  73566. }
  73567. }
  73568. p = p.next;
  73569. } while (p !== outerNode);
  73570. if (!m)
  73571. return null;
  73572. if (hx === qx)
  73573. return m.prev; // hole touches outer segment; pick lower endpoint
  73574. // look for points inside the triangle of hole point, segment intersection and endpoint;
  73575. // if there are no points found, we have a valid connection;
  73576. // otherwise choose the point of the minimum angle with the ray as connection point
  73577. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  73578. p = m.next;
  73579. while (p !== stop) {
  73580. if (hx >= p.x &&
  73581. p.x >= mx &&
  73582. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  73583. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  73584. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  73585. m = p;
  73586. tanMin = tan;
  73587. }
  73588. }
  73589. p = p.next;
  73590. }
  73591. return m;
  73592. }
  73593. // interlink polygon nodes in z-order
  73594. function indexCurve(start, minX, minY, size) {
  73595. var p = start;
  73596. do {
  73597. if (p.z === null)
  73598. p.z = zOrder(p.x, p.y, minX, minY, size);
  73599. p.prevZ = p.prev;
  73600. p.nextZ = p.next;
  73601. p = p.next;
  73602. } while (p !== start);
  73603. p.prevZ.nextZ = null;
  73604. p.prevZ = null;
  73605. sortLinked(p);
  73606. }
  73607. // Simon Tatham's linked list merge sort algorithm
  73608. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  73609. function sortLinked(list) {
  73610. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  73611. do {
  73612. p = list;
  73613. list = null;
  73614. tail = null;
  73615. numMerges = 0;
  73616. while (p) {
  73617. numMerges++;
  73618. q = p;
  73619. pSize = 0;
  73620. for (i = 0; i < inSize; i++) {
  73621. pSize++;
  73622. q = q.nextZ;
  73623. if (!q)
  73624. break;
  73625. }
  73626. qSize = inSize;
  73627. while (pSize > 0 || (qSize > 0 && q)) {
  73628. if (pSize === 0) {
  73629. e = q;
  73630. q = q.nextZ;
  73631. qSize--;
  73632. }
  73633. else if (qSize === 0 || !q) {
  73634. e = p;
  73635. p = p.nextZ;
  73636. pSize--;
  73637. }
  73638. else if (p.z <= q.z) {
  73639. e = p;
  73640. p = p.nextZ;
  73641. pSize--;
  73642. }
  73643. else {
  73644. e = q;
  73645. q = q.nextZ;
  73646. qSize--;
  73647. }
  73648. if (tail)
  73649. tail.nextZ = e;
  73650. else
  73651. list = e;
  73652. e.prevZ = tail;
  73653. tail = e;
  73654. }
  73655. p = q;
  73656. }
  73657. tail.nextZ = null;
  73658. inSize *= 2;
  73659. } while (numMerges > 1);
  73660. return list;
  73661. }
  73662. // z-order of a point given coords and size of the data bounding box
  73663. function zOrder(x, y, minX, minY, size) {
  73664. // coords are transformed into non-negative 15-bit integer range
  73665. x = 32767 * (x - minX) / size;
  73666. y = 32767 * (y - minY) / size;
  73667. x = (x | (x << 8)) & 0x00FF00FF;
  73668. x = (x | (x << 4)) & 0x0F0F0F0F;
  73669. x = (x | (x << 2)) & 0x33333333;
  73670. x = (x | (x << 1)) & 0x55555555;
  73671. y = (y | (y << 8)) & 0x00FF00FF;
  73672. y = (y | (y << 4)) & 0x0F0F0F0F;
  73673. y = (y | (y << 2)) & 0x33333333;
  73674. y = (y | (y << 1)) & 0x55555555;
  73675. return x | (y << 1);
  73676. }
  73677. // find the leftmost node of a polygon ring
  73678. function getLeftmost(start) {
  73679. var p = start, leftmost = start;
  73680. do {
  73681. if (p.x < leftmost.x)
  73682. leftmost = p;
  73683. p = p.next;
  73684. } while (p !== start);
  73685. return leftmost;
  73686. }
  73687. // check if a point lies within a convex triangle
  73688. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  73689. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  73690. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  73691. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  73692. }
  73693. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  73694. function isValidDiagonal(a, b) {
  73695. return a.next.i !== b.i &&
  73696. a.prev.i !== b.i &&
  73697. !intersectsPolygon(a, b) &&
  73698. locallyInside(a, b) &&
  73699. locallyInside(b, a) &&
  73700. middleInside(a, b);
  73701. }
  73702. // signed area of a triangle
  73703. function area(p, q, r) {
  73704. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  73705. }
  73706. // check if two points are equal
  73707. function equals(p1, p2) {
  73708. return p1.x === p2.x && p1.y === p2.y;
  73709. }
  73710. // check if two segments intersect
  73711. function intersects(p1, q1, p2, q2) {
  73712. if ((equals(p1, q1) && equals(p2, q2)) ||
  73713. (equals(p1, q2) && equals(p2, q1)))
  73714. return true;
  73715. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  73716. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  73717. }
  73718. // check if a polygon diagonal intersects any polygon segments
  73719. function intersectsPolygon(a, b) {
  73720. var p = a;
  73721. do {
  73722. if (p.i !== a.i &&
  73723. p.next.i !== a.i &&
  73724. p.i !== b.i &&
  73725. p.next.i !== b.i &&
  73726. intersects(p, p.next, a, b))
  73727. return true;
  73728. p = p.next;
  73729. } while (p !== a);
  73730. return false;
  73731. }
  73732. // check if a polygon diagonal is locally inside the polygon
  73733. function locallyInside(a, b) {
  73734. return area(a.prev, a, a.next) < 0
  73735. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  73736. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  73737. }
  73738. // check if the middle point of a polygon diagonal is inside the polygon
  73739. function middleInside(a, b) {
  73740. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  73741. do {
  73742. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  73743. inside = !inside;
  73744. p = p.next;
  73745. } while (p !== a);
  73746. return inside;
  73747. }
  73748. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  73749. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  73750. function splitPolygon(a, b) {
  73751. var a2 = new Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev;
  73752. a.next = b;
  73753. b.prev = a;
  73754. a2.next = an;
  73755. an.prev = a2;
  73756. b2.next = a2;
  73757. a2.prev = b2;
  73758. bp.next = b2;
  73759. b2.prev = bp;
  73760. return b2;
  73761. }
  73762. // create a node and optionally link it with previous one (in a circular doubly linked list)
  73763. function insertNode(i, x, y, last) {
  73764. var p = new Node(i, x, y);
  73765. if (!last) {
  73766. p.prev = p;
  73767. p.next = p;
  73768. }
  73769. else {
  73770. p.next = last.next;
  73771. p.prev = last;
  73772. last.next.prev = p;
  73773. last.next = p;
  73774. }
  73775. return p;
  73776. }
  73777. function removeNode(p) {
  73778. p.next.prev = p.prev;
  73779. p.prev.next = p.next;
  73780. if (p.prevZ)
  73781. p.prevZ.nextZ = p.nextZ;
  73782. if (p.nextZ)
  73783. p.nextZ.prevZ = p.prevZ;
  73784. }
  73785. /**
  73786. * return a percentage difference between the polygon area and its triangulation area;
  73787. * used to verify correctness of triangulation
  73788. */
  73789. function deviation(data, holeIndices, dim, triangles) {
  73790. var hasHoles = holeIndices && holeIndices.length;
  73791. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  73792. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  73793. if (hasHoles) {
  73794. for (var i = 0, len = holeIndices.length; i < len; i++) {
  73795. var start = holeIndices[i] * dim;
  73796. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  73797. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  73798. }
  73799. }
  73800. var trianglesArea = 0;
  73801. for (i = 0; i < triangles.length; i += 3) {
  73802. var a = triangles[i] * dim;
  73803. var b = triangles[i + 1] * dim;
  73804. var c = triangles[i + 2] * dim;
  73805. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  73806. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  73807. }
  73808. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  73809. }
  73810. Earcut.deviation = deviation;
  73811. ;
  73812. function signedArea(data, start, end, dim) {
  73813. var sum = 0;
  73814. for (var i = start, j = end - dim; i < end; i += dim) {
  73815. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  73816. j = i;
  73817. }
  73818. return sum;
  73819. }
  73820. /**
  73821. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  73822. */
  73823. function flatten(data) {
  73824. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  73825. for (var i = 0; i < data.length; i++) {
  73826. for (var j = 0; j < data[i].length; j++) {
  73827. for (var d = 0; d < dim; d++)
  73828. result.vertices.push(data[i][j][d]);
  73829. }
  73830. if (i > 0) {
  73831. holeIndex += data[i - 1].length;
  73832. result.holes.push(holeIndex);
  73833. }
  73834. }
  73835. return result;
  73836. }
  73837. Earcut.flatten = flatten;
  73838. ;
  73839. })(Earcut || (Earcut = {}));
  73840. //# sourceMappingURL=babylon.earcut.js.map
  73841. var BABYLON;
  73842. (function (BABYLON) {
  73843. var IndexedVector2 = /** @class */ (function (_super) {
  73844. __extends(IndexedVector2, _super);
  73845. function IndexedVector2(original, index) {
  73846. var _this = _super.call(this, original.x, original.y) || this;
  73847. _this.index = index;
  73848. return _this;
  73849. }
  73850. return IndexedVector2;
  73851. }(BABYLON.Vector2));
  73852. var PolygonPoints = /** @class */ (function () {
  73853. function PolygonPoints() {
  73854. this.elements = new Array();
  73855. }
  73856. PolygonPoints.prototype.add = function (originalPoints) {
  73857. var _this = this;
  73858. var result = new Array();
  73859. originalPoints.forEach(function (point) {
  73860. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  73861. var newPoint = new IndexedVector2(point, _this.elements.length);
  73862. result.push(newPoint);
  73863. _this.elements.push(newPoint);
  73864. }
  73865. });
  73866. return result;
  73867. };
  73868. PolygonPoints.prototype.computeBounds = function () {
  73869. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  73870. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  73871. this.elements.forEach(function (point) {
  73872. // x
  73873. if (point.x < lmin.x) {
  73874. lmin.x = point.x;
  73875. }
  73876. else if (point.x > lmax.x) {
  73877. lmax.x = point.x;
  73878. }
  73879. // y
  73880. if (point.y < lmin.y) {
  73881. lmin.y = point.y;
  73882. }
  73883. else if (point.y > lmax.y) {
  73884. lmax.y = point.y;
  73885. }
  73886. });
  73887. return {
  73888. min: lmin,
  73889. max: lmax,
  73890. width: lmax.x - lmin.x,
  73891. height: lmax.y - lmin.y
  73892. };
  73893. };
  73894. return PolygonPoints;
  73895. }());
  73896. var Polygon = /** @class */ (function () {
  73897. function Polygon() {
  73898. }
  73899. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  73900. return [
  73901. new BABYLON.Vector2(xmin, ymin),
  73902. new BABYLON.Vector2(xmax, ymin),
  73903. new BABYLON.Vector2(xmax, ymax),
  73904. new BABYLON.Vector2(xmin, ymax)
  73905. ];
  73906. };
  73907. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  73908. if (cx === void 0) { cx = 0; }
  73909. if (cy === void 0) { cy = 0; }
  73910. if (numberOfSides === void 0) { numberOfSides = 32; }
  73911. var result = new Array();
  73912. var angle = 0;
  73913. var increment = (Math.PI * 2) / numberOfSides;
  73914. for (var i = 0; i < numberOfSides; i++) {
  73915. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  73916. angle -= increment;
  73917. }
  73918. return result;
  73919. };
  73920. Polygon.Parse = function (input) {
  73921. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  73922. var i, result = [];
  73923. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  73924. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  73925. }
  73926. return result;
  73927. };
  73928. Polygon.StartingAt = function (x, y) {
  73929. return BABYLON.Path2.StartingAt(x, y);
  73930. };
  73931. return Polygon;
  73932. }());
  73933. BABYLON.Polygon = Polygon;
  73934. var PolygonMeshBuilder = /** @class */ (function () {
  73935. function PolygonMeshBuilder(name, contours, scene) {
  73936. this._points = new PolygonPoints();
  73937. this._outlinepoints = new PolygonPoints();
  73938. this._holes = new Array();
  73939. this._epoints = new Array();
  73940. this._eholes = new Array();
  73941. this._name = name;
  73942. this._scene = scene;
  73943. var points;
  73944. if (contours instanceof BABYLON.Path2) {
  73945. points = contours.getPoints();
  73946. }
  73947. else {
  73948. points = contours;
  73949. }
  73950. this._addToepoint(points);
  73951. this._points.add(points);
  73952. this._outlinepoints.add(points);
  73953. }
  73954. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  73955. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  73956. var p = points_1[_i];
  73957. this._epoints.push(p.x, p.y);
  73958. }
  73959. };
  73960. PolygonMeshBuilder.prototype.addHole = function (hole) {
  73961. this._points.add(hole);
  73962. var holepoints = new PolygonPoints();
  73963. holepoints.add(hole);
  73964. this._holes.push(holepoints);
  73965. this._eholes.push(this._epoints.length / 2);
  73966. this._addToepoint(hole);
  73967. return this;
  73968. };
  73969. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  73970. var _this = this;
  73971. if (updatable === void 0) { updatable = false; }
  73972. if (depth === void 0) { depth = 0; }
  73973. var result = new BABYLON.Mesh(this._name, this._scene);
  73974. var normals = new Array();
  73975. var positions = new Array();
  73976. var uvs = new Array();
  73977. var bounds = this._points.computeBounds();
  73978. this._points.elements.forEach(function (p) {
  73979. normals.push(0, 1.0, 0);
  73980. positions.push(p.x, 0, p.y);
  73981. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  73982. });
  73983. var indices = new Array();
  73984. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  73985. for (var i = 0; i < res.length; i++) {
  73986. indices.push(res[i]);
  73987. }
  73988. if (depth > 0) {
  73989. var positionscount = (positions.length / 3); //get the current pointcount
  73990. this._points.elements.forEach(function (p) {
  73991. normals.push(0, -1.0, 0);
  73992. positions.push(p.x, -depth, p.y);
  73993. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  73994. });
  73995. var totalCount = indices.length;
  73996. for (var i = 0; i < totalCount; i += 3) {
  73997. var i0 = indices[i + 0];
  73998. var i1 = indices[i + 1];
  73999. var i2 = indices[i + 2];
  74000. indices.push(i2 + positionscount);
  74001. indices.push(i1 + positionscount);
  74002. indices.push(i0 + positionscount);
  74003. }
  74004. //Add the sides
  74005. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  74006. this._holes.forEach(function (hole) {
  74007. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  74008. });
  74009. }
  74010. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  74011. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  74012. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  74013. result.setIndices(indices);
  74014. return result;
  74015. };
  74016. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  74017. var StartIndex = positions.length / 3;
  74018. var ulength = 0;
  74019. for (var i = 0; i < points.elements.length; i++) {
  74020. var p = points.elements[i];
  74021. var p1;
  74022. if ((i + 1) > points.elements.length - 1) {
  74023. p1 = points.elements[0];
  74024. }
  74025. else {
  74026. p1 = points.elements[i + 1];
  74027. }
  74028. positions.push(p.x, 0, p.y);
  74029. positions.push(p.x, -depth, p.y);
  74030. positions.push(p1.x, 0, p1.y);
  74031. positions.push(p1.x, -depth, p1.y);
  74032. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  74033. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  74034. var v3 = v2.subtract(v1);
  74035. var v4 = new BABYLON.Vector3(0, 1, 0);
  74036. var vn = BABYLON.Vector3.Cross(v3, v4);
  74037. vn = vn.normalize();
  74038. uvs.push(ulength / bounds.width, 0);
  74039. uvs.push(ulength / bounds.width, 1);
  74040. ulength += v3.length();
  74041. uvs.push((ulength / bounds.width), 0);
  74042. uvs.push((ulength / bounds.width), 1);
  74043. if (!flip) {
  74044. normals.push(-vn.x, -vn.y, -vn.z);
  74045. normals.push(-vn.x, -vn.y, -vn.z);
  74046. normals.push(-vn.x, -vn.y, -vn.z);
  74047. normals.push(-vn.x, -vn.y, -vn.z);
  74048. indices.push(StartIndex);
  74049. indices.push(StartIndex + 1);
  74050. indices.push(StartIndex + 2);
  74051. indices.push(StartIndex + 1);
  74052. indices.push(StartIndex + 3);
  74053. indices.push(StartIndex + 2);
  74054. }
  74055. else {
  74056. normals.push(vn.x, vn.y, vn.z);
  74057. normals.push(vn.x, vn.y, vn.z);
  74058. normals.push(vn.x, vn.y, vn.z);
  74059. normals.push(vn.x, vn.y, vn.z);
  74060. indices.push(StartIndex);
  74061. indices.push(StartIndex + 2);
  74062. indices.push(StartIndex + 1);
  74063. indices.push(StartIndex + 1);
  74064. indices.push(StartIndex + 2);
  74065. indices.push(StartIndex + 3);
  74066. }
  74067. StartIndex += 4;
  74068. }
  74069. ;
  74070. };
  74071. return PolygonMeshBuilder;
  74072. }());
  74073. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  74074. })(BABYLON || (BABYLON = {}));
  74075. //# sourceMappingURL=babylon.polygonMesh.js.map
  74076. var BABYLON;
  74077. (function (BABYLON) {
  74078. // Unique ID when we import meshes from Babylon to CSG
  74079. var currentCSGMeshId = 0;
  74080. // # class Vertex
  74081. // Represents a vertex of a polygon. Use your own vertex class instead of this
  74082. // one to provide additional features like texture coordinates and vertex
  74083. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  74084. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  74085. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  74086. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  74087. // is not used anywhere else.
  74088. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  74089. var Vertex = /** @class */ (function () {
  74090. function Vertex(pos, normal, uv) {
  74091. this.pos = pos;
  74092. this.normal = normal;
  74093. this.uv = uv;
  74094. }
  74095. Vertex.prototype.clone = function () {
  74096. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  74097. };
  74098. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  74099. // orientation of a polygon is flipped.
  74100. Vertex.prototype.flip = function () {
  74101. this.normal = this.normal.scale(-1);
  74102. };
  74103. // Create a new vertex between this vertex and `other` by linearly
  74104. // interpolating all properties using a parameter of `t`. Subclasses should
  74105. // override this to interpolate additional properties.
  74106. Vertex.prototype.interpolate = function (other, t) {
  74107. 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));
  74108. };
  74109. return Vertex;
  74110. }());
  74111. // # class Plane
  74112. // Represents a plane in 3D space.
  74113. var Plane = /** @class */ (function () {
  74114. function Plane(normal, w) {
  74115. this.normal = normal;
  74116. this.w = w;
  74117. }
  74118. Plane.FromPoints = function (a, b, c) {
  74119. var v0 = c.subtract(a);
  74120. var v1 = b.subtract(a);
  74121. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  74122. return null;
  74123. }
  74124. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  74125. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  74126. };
  74127. Plane.prototype.clone = function () {
  74128. return new Plane(this.normal.clone(), this.w);
  74129. };
  74130. Plane.prototype.flip = function () {
  74131. this.normal.scaleInPlace(-1);
  74132. this.w = -this.w;
  74133. };
  74134. // Split `polygon` by this plane if needed, then put the polygon or polygon
  74135. // fragments in the appropriate lists. Coplanar polygons go into either
  74136. // `coplanarFront` or `coplanarBack` depending on their orientation with
  74137. // respect to this plane. Polygons in front or in back of this plane go into
  74138. // either `front` or `back`.
  74139. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  74140. var COPLANAR = 0;
  74141. var FRONT = 1;
  74142. var BACK = 2;
  74143. var SPANNING = 3;
  74144. // Classify each point as well as the entire polygon into one of the above
  74145. // four classes.
  74146. var polygonType = 0;
  74147. var types = [];
  74148. var i;
  74149. var t;
  74150. for (i = 0; i < polygon.vertices.length; i++) {
  74151. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  74152. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  74153. polygonType |= type;
  74154. types.push(type);
  74155. }
  74156. // Put the polygon in the correct list, splitting it when necessary.
  74157. switch (polygonType) {
  74158. case COPLANAR:
  74159. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  74160. break;
  74161. case FRONT:
  74162. front.push(polygon);
  74163. break;
  74164. case BACK:
  74165. back.push(polygon);
  74166. break;
  74167. case SPANNING:
  74168. var f = [], b = [];
  74169. for (i = 0; i < polygon.vertices.length; i++) {
  74170. var j = (i + 1) % polygon.vertices.length;
  74171. var ti = types[i], tj = types[j];
  74172. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  74173. if (ti !== BACK)
  74174. f.push(vi);
  74175. if (ti !== FRONT)
  74176. b.push(ti !== BACK ? vi.clone() : vi);
  74177. if ((ti | tj) === SPANNING) {
  74178. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  74179. var v = vi.interpolate(vj, t);
  74180. f.push(v);
  74181. b.push(v.clone());
  74182. }
  74183. }
  74184. var poly;
  74185. if (f.length >= 3) {
  74186. poly = new Polygon(f, polygon.shared);
  74187. if (poly.plane)
  74188. front.push(poly);
  74189. }
  74190. if (b.length >= 3) {
  74191. poly = new Polygon(b, polygon.shared);
  74192. if (poly.plane)
  74193. back.push(poly);
  74194. }
  74195. break;
  74196. }
  74197. };
  74198. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  74199. // point is on the plane.
  74200. Plane.EPSILON = 1e-5;
  74201. return Plane;
  74202. }());
  74203. // # class Polygon
  74204. // Represents a convex polygon. The vertices used to initialize a polygon must
  74205. // be coplanar and form a convex loop.
  74206. //
  74207. // Each convex polygon has a `shared` property, which is shared between all
  74208. // polygons that are clones of each other or were split from the same polygon.
  74209. // This can be used to define per-polygon properties (such as surface color).
  74210. var Polygon = /** @class */ (function () {
  74211. function Polygon(vertices, shared) {
  74212. this.vertices = vertices;
  74213. this.shared = shared;
  74214. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  74215. }
  74216. Polygon.prototype.clone = function () {
  74217. var vertices = this.vertices.map(function (v) { return v.clone(); });
  74218. return new Polygon(vertices, this.shared);
  74219. };
  74220. Polygon.prototype.flip = function () {
  74221. this.vertices.reverse().map(function (v) { v.flip(); });
  74222. this.plane.flip();
  74223. };
  74224. return Polygon;
  74225. }());
  74226. // # class Node
  74227. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  74228. // by picking a polygon to split along. That polygon (and all other coplanar
  74229. // polygons) are added directly to that node and the other polygons are added to
  74230. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  74231. // no distinction between internal and leaf nodes.
  74232. var Node = /** @class */ (function () {
  74233. function Node(polygons) {
  74234. this.plane = null;
  74235. this.front = null;
  74236. this.back = null;
  74237. this.polygons = new Array();
  74238. if (polygons) {
  74239. this.build(polygons);
  74240. }
  74241. }
  74242. Node.prototype.clone = function () {
  74243. var node = new Node();
  74244. node.plane = this.plane && this.plane.clone();
  74245. node.front = this.front && this.front.clone();
  74246. node.back = this.back && this.back.clone();
  74247. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  74248. return node;
  74249. };
  74250. // Convert solid space to empty space and empty space to solid space.
  74251. Node.prototype.invert = function () {
  74252. for (var i = 0; i < this.polygons.length; i++) {
  74253. this.polygons[i].flip();
  74254. }
  74255. if (this.plane) {
  74256. this.plane.flip();
  74257. }
  74258. if (this.front) {
  74259. this.front.invert();
  74260. }
  74261. if (this.back) {
  74262. this.back.invert();
  74263. }
  74264. var temp = this.front;
  74265. this.front = this.back;
  74266. this.back = temp;
  74267. };
  74268. // Recursively remove all polygons in `polygons` that are inside this BSP
  74269. // tree.
  74270. Node.prototype.clipPolygons = function (polygons) {
  74271. if (!this.plane)
  74272. return polygons.slice();
  74273. var front = new Array(), back = new Array();
  74274. for (var i = 0; i < polygons.length; i++) {
  74275. this.plane.splitPolygon(polygons[i], front, back, front, back);
  74276. }
  74277. if (this.front) {
  74278. front = this.front.clipPolygons(front);
  74279. }
  74280. if (this.back) {
  74281. back = this.back.clipPolygons(back);
  74282. }
  74283. else {
  74284. back = [];
  74285. }
  74286. return front.concat(back);
  74287. };
  74288. // Remove all polygons in this BSP tree that are inside the other BSP tree
  74289. // `bsp`.
  74290. Node.prototype.clipTo = function (bsp) {
  74291. this.polygons = bsp.clipPolygons(this.polygons);
  74292. if (this.front)
  74293. this.front.clipTo(bsp);
  74294. if (this.back)
  74295. this.back.clipTo(bsp);
  74296. };
  74297. // Return a list of all polygons in this BSP tree.
  74298. Node.prototype.allPolygons = function () {
  74299. var polygons = this.polygons.slice();
  74300. if (this.front)
  74301. polygons = polygons.concat(this.front.allPolygons());
  74302. if (this.back)
  74303. polygons = polygons.concat(this.back.allPolygons());
  74304. return polygons;
  74305. };
  74306. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  74307. // new polygons are filtered down to the bottom of the tree and become new
  74308. // nodes there. Each set of polygons is partitioned using the first polygon
  74309. // (no heuristic is used to pick a good split).
  74310. Node.prototype.build = function (polygons) {
  74311. if (!polygons.length)
  74312. return;
  74313. if (!this.plane)
  74314. this.plane = polygons[0].plane.clone();
  74315. var front = new Array(), back = new Array();
  74316. for (var i = 0; i < polygons.length; i++) {
  74317. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  74318. }
  74319. if (front.length) {
  74320. if (!this.front)
  74321. this.front = new Node();
  74322. this.front.build(front);
  74323. }
  74324. if (back.length) {
  74325. if (!this.back)
  74326. this.back = new Node();
  74327. this.back.build(back);
  74328. }
  74329. };
  74330. return Node;
  74331. }());
  74332. var CSG = /** @class */ (function () {
  74333. function CSG() {
  74334. this.polygons = new Array();
  74335. }
  74336. // Convert BABYLON.Mesh to BABYLON.CSG
  74337. CSG.FromMesh = function (mesh) {
  74338. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  74339. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  74340. if (mesh instanceof BABYLON.Mesh) {
  74341. mesh.computeWorldMatrix(true);
  74342. matrix = mesh.getWorldMatrix();
  74343. meshPosition = mesh.position.clone();
  74344. meshRotation = mesh.rotation.clone();
  74345. if (mesh.rotationQuaternion) {
  74346. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  74347. }
  74348. meshScaling = mesh.scaling.clone();
  74349. }
  74350. else {
  74351. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  74352. }
  74353. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  74354. var subMeshes = mesh.subMeshes;
  74355. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  74356. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  74357. vertices = [];
  74358. for (var j = 0; j < 3; j++) {
  74359. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  74360. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  74361. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  74362. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  74363. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  74364. vertex = new Vertex(position, normal, uv);
  74365. vertices.push(vertex);
  74366. }
  74367. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  74368. // To handle the case of degenerated triangle
  74369. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  74370. if (polygon.plane)
  74371. polygons.push(polygon);
  74372. }
  74373. }
  74374. var csg = CSG.FromPolygons(polygons);
  74375. csg.matrix = matrix;
  74376. csg.position = meshPosition;
  74377. csg.rotation = meshRotation;
  74378. csg.scaling = meshScaling;
  74379. csg.rotationQuaternion = meshRotationQuaternion;
  74380. currentCSGMeshId++;
  74381. return csg;
  74382. };
  74383. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  74384. CSG.FromPolygons = function (polygons) {
  74385. var csg = new CSG();
  74386. csg.polygons = polygons;
  74387. return csg;
  74388. };
  74389. CSG.prototype.clone = function () {
  74390. var csg = new CSG();
  74391. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  74392. csg.copyTransformAttributes(this);
  74393. return csg;
  74394. };
  74395. CSG.prototype.union = function (csg) {
  74396. var a = new Node(this.clone().polygons);
  74397. var b = new Node(csg.clone().polygons);
  74398. a.clipTo(b);
  74399. b.clipTo(a);
  74400. b.invert();
  74401. b.clipTo(a);
  74402. b.invert();
  74403. a.build(b.allPolygons());
  74404. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  74405. };
  74406. CSG.prototype.unionInPlace = function (csg) {
  74407. var a = new Node(this.polygons);
  74408. var b = new Node(csg.polygons);
  74409. a.clipTo(b);
  74410. b.clipTo(a);
  74411. b.invert();
  74412. b.clipTo(a);
  74413. b.invert();
  74414. a.build(b.allPolygons());
  74415. this.polygons = a.allPolygons();
  74416. };
  74417. CSG.prototype.subtract = function (csg) {
  74418. var a = new Node(this.clone().polygons);
  74419. var b = new Node(csg.clone().polygons);
  74420. a.invert();
  74421. a.clipTo(b);
  74422. b.clipTo(a);
  74423. b.invert();
  74424. b.clipTo(a);
  74425. b.invert();
  74426. a.build(b.allPolygons());
  74427. a.invert();
  74428. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  74429. };
  74430. CSG.prototype.subtractInPlace = function (csg) {
  74431. var a = new Node(this.polygons);
  74432. var b = new Node(csg.polygons);
  74433. a.invert();
  74434. a.clipTo(b);
  74435. b.clipTo(a);
  74436. b.invert();
  74437. b.clipTo(a);
  74438. b.invert();
  74439. a.build(b.allPolygons());
  74440. a.invert();
  74441. this.polygons = a.allPolygons();
  74442. };
  74443. CSG.prototype.intersect = function (csg) {
  74444. var a = new Node(this.clone().polygons);
  74445. var b = new Node(csg.clone().polygons);
  74446. a.invert();
  74447. b.clipTo(a);
  74448. b.invert();
  74449. a.clipTo(b);
  74450. b.clipTo(a);
  74451. a.build(b.allPolygons());
  74452. a.invert();
  74453. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  74454. };
  74455. CSG.prototype.intersectInPlace = function (csg) {
  74456. var a = new Node(this.polygons);
  74457. var b = new Node(csg.polygons);
  74458. a.invert();
  74459. b.clipTo(a);
  74460. b.invert();
  74461. a.clipTo(b);
  74462. b.clipTo(a);
  74463. a.build(b.allPolygons());
  74464. a.invert();
  74465. this.polygons = a.allPolygons();
  74466. };
  74467. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  74468. // not modified.
  74469. CSG.prototype.inverse = function () {
  74470. var csg = this.clone();
  74471. csg.inverseInPlace();
  74472. return csg;
  74473. };
  74474. CSG.prototype.inverseInPlace = function () {
  74475. this.polygons.map(function (p) { p.flip(); });
  74476. };
  74477. // This is used to keep meshes transformations so they can be restored
  74478. // when we build back a Babylon Mesh
  74479. // NB : All CSG operations are performed in world coordinates
  74480. CSG.prototype.copyTransformAttributes = function (csg) {
  74481. this.matrix = csg.matrix;
  74482. this.position = csg.position;
  74483. this.rotation = csg.rotation;
  74484. this.scaling = csg.scaling;
  74485. this.rotationQuaternion = csg.rotationQuaternion;
  74486. return this;
  74487. };
  74488. // Build Raw mesh from CSG
  74489. // Coordinates here are in world space
  74490. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  74491. var matrix = this.matrix.clone();
  74492. matrix.invert();
  74493. 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;
  74494. if (keepSubMeshes) {
  74495. // Sort Polygons, since subMeshes are indices range
  74496. polygons.sort(function (a, b) {
  74497. if (a.shared.meshId === b.shared.meshId) {
  74498. return a.shared.subMeshId - b.shared.subMeshId;
  74499. }
  74500. else {
  74501. return a.shared.meshId - b.shared.meshId;
  74502. }
  74503. });
  74504. }
  74505. for (var i = 0, il = polygons.length; i < il; i++) {
  74506. polygon = polygons[i];
  74507. // Building SubMeshes
  74508. if (!subMesh_dict[polygon.shared.meshId]) {
  74509. subMesh_dict[polygon.shared.meshId] = {};
  74510. }
  74511. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  74512. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  74513. indexStart: +Infinity,
  74514. indexEnd: -Infinity,
  74515. materialIndex: polygon.shared.materialIndex
  74516. };
  74517. }
  74518. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  74519. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  74520. polygonIndices[0] = 0;
  74521. polygonIndices[1] = j - 1;
  74522. polygonIndices[2] = j;
  74523. for (var k = 0; k < 3; k++) {
  74524. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  74525. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  74526. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  74527. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  74528. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  74529. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  74530. // Check if 2 points can be merged
  74531. if (!(typeof vertex_idx !== 'undefined' &&
  74532. normals[vertex_idx * 3] === localNormal.x &&
  74533. normals[vertex_idx * 3 + 1] === localNormal.y &&
  74534. normals[vertex_idx * 3 + 2] === localNormal.z &&
  74535. uvs[vertex_idx * 2] === uv.x &&
  74536. uvs[vertex_idx * 2 + 1] === uv.y)) {
  74537. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  74538. uvs.push(uv.x, uv.y);
  74539. normals.push(normal.x, normal.y, normal.z);
  74540. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  74541. }
  74542. indices.push(vertex_idx);
  74543. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  74544. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  74545. currentIndex++;
  74546. }
  74547. }
  74548. }
  74549. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  74550. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  74551. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  74552. mesh.setIndices(indices, null);
  74553. if (keepSubMeshes) {
  74554. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  74555. var materialIndexOffset = 0, materialMaxIndex;
  74556. mesh.subMeshes = new Array();
  74557. for (var m in subMesh_dict) {
  74558. materialMaxIndex = -1;
  74559. for (var sm in subMesh_dict[m]) {
  74560. subMesh_obj = subMesh_dict[m][sm];
  74561. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  74562. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  74563. }
  74564. materialIndexOffset += ++materialMaxIndex;
  74565. }
  74566. }
  74567. return mesh;
  74568. };
  74569. // Build Mesh from CSG taking material and transforms into account
  74570. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  74571. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  74572. mesh.material = material;
  74573. mesh.position.copyFrom(this.position);
  74574. mesh.rotation.copyFrom(this.rotation);
  74575. if (this.rotationQuaternion) {
  74576. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  74577. }
  74578. mesh.scaling.copyFrom(this.scaling);
  74579. mesh.computeWorldMatrix(true);
  74580. return mesh;
  74581. };
  74582. return CSG;
  74583. }());
  74584. BABYLON.CSG = CSG;
  74585. })(BABYLON || (BABYLON = {}));
  74586. //# sourceMappingURL=babylon.csg.js.map
  74587. var BABYLON;
  74588. (function (BABYLON) {
  74589. var LensFlare = /** @class */ (function () {
  74590. function LensFlare(size, position, color, imgUrl, system) {
  74591. this.size = size;
  74592. this.position = position;
  74593. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  74594. this.color = color || new BABYLON.Color3(1, 1, 1);
  74595. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  74596. this._system = system;
  74597. system.lensFlares.push(this);
  74598. }
  74599. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  74600. return new LensFlare(size, position, color, imgUrl, system);
  74601. };
  74602. LensFlare.prototype.dispose = function () {
  74603. if (this.texture) {
  74604. this.texture.dispose();
  74605. }
  74606. // Remove from scene
  74607. var index = this._system.lensFlares.indexOf(this);
  74608. this._system.lensFlares.splice(index, 1);
  74609. };
  74610. ;
  74611. return LensFlare;
  74612. }());
  74613. BABYLON.LensFlare = LensFlare;
  74614. })(BABYLON || (BABYLON = {}));
  74615. //# sourceMappingURL=babylon.lensFlare.js.map
  74616. var BABYLON;
  74617. (function (BABYLON) {
  74618. var LensFlareSystem = /** @class */ (function () {
  74619. function LensFlareSystem(name, emitter, scene) {
  74620. this.name = name;
  74621. this.lensFlares = new Array();
  74622. this.borderLimit = 300;
  74623. this.viewportBorder = 0;
  74624. this.layerMask = 0x0FFFFFFF;
  74625. this._vertexBuffers = {};
  74626. this._isEnabled = true;
  74627. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  74628. this._emitter = emitter;
  74629. this.id = name;
  74630. scene.lensFlareSystems.push(this);
  74631. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  74632. var engine = scene.getEngine();
  74633. // VBO
  74634. var vertices = [];
  74635. vertices.push(1, 1);
  74636. vertices.push(-1, 1);
  74637. vertices.push(-1, -1);
  74638. vertices.push(1, -1);
  74639. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  74640. // Indices
  74641. var indices = [];
  74642. indices.push(0);
  74643. indices.push(1);
  74644. indices.push(2);
  74645. indices.push(0);
  74646. indices.push(2);
  74647. indices.push(3);
  74648. this._indexBuffer = engine.createIndexBuffer(indices);
  74649. // Effects
  74650. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  74651. }
  74652. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  74653. get: function () {
  74654. return this._isEnabled;
  74655. },
  74656. set: function (value) {
  74657. this._isEnabled = value;
  74658. },
  74659. enumerable: true,
  74660. configurable: true
  74661. });
  74662. LensFlareSystem.prototype.getScene = function () {
  74663. return this._scene;
  74664. };
  74665. LensFlareSystem.prototype.getEmitter = function () {
  74666. return this._emitter;
  74667. };
  74668. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  74669. this._emitter = newEmitter;
  74670. };
  74671. LensFlareSystem.prototype.getEmitterPosition = function () {
  74672. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  74673. };
  74674. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  74675. var position = this.getEmitterPosition();
  74676. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  74677. this._positionX = position.x;
  74678. this._positionY = position.y;
  74679. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  74680. if (this.viewportBorder > 0) {
  74681. globalViewport.x -= this.viewportBorder;
  74682. globalViewport.y -= this.viewportBorder;
  74683. globalViewport.width += this.viewportBorder * 2;
  74684. globalViewport.height += this.viewportBorder * 2;
  74685. position.x += this.viewportBorder;
  74686. position.y += this.viewportBorder;
  74687. this._positionX += this.viewportBorder;
  74688. this._positionY += this.viewportBorder;
  74689. }
  74690. if (position.z > 0) {
  74691. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  74692. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  74693. return true;
  74694. }
  74695. return true;
  74696. }
  74697. return false;
  74698. };
  74699. LensFlareSystem.prototype._isVisible = function () {
  74700. if (!this._isEnabled || !this._scene.activeCamera) {
  74701. return false;
  74702. }
  74703. var emitterPosition = this.getEmitterPosition();
  74704. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  74705. var distance = direction.length();
  74706. direction.normalize();
  74707. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  74708. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  74709. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  74710. };
  74711. LensFlareSystem.prototype.render = function () {
  74712. if (!this._effect.isReady() || !this._scene.activeCamera)
  74713. return false;
  74714. var engine = this._scene.getEngine();
  74715. var viewport = this._scene.activeCamera.viewport;
  74716. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  74717. // Position
  74718. if (!this.computeEffectivePosition(globalViewport)) {
  74719. return false;
  74720. }
  74721. // Visibility
  74722. if (!this._isVisible()) {
  74723. return false;
  74724. }
  74725. // Intensity
  74726. var awayX;
  74727. var awayY;
  74728. if (this._positionX < this.borderLimit + globalViewport.x) {
  74729. awayX = this.borderLimit + globalViewport.x - this._positionX;
  74730. }
  74731. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  74732. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  74733. }
  74734. else {
  74735. awayX = 0;
  74736. }
  74737. if (this._positionY < this.borderLimit + globalViewport.y) {
  74738. awayY = this.borderLimit + globalViewport.y - this._positionY;
  74739. }
  74740. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  74741. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  74742. }
  74743. else {
  74744. awayY = 0;
  74745. }
  74746. var away = (awayX > awayY) ? awayX : awayY;
  74747. away -= this.viewportBorder;
  74748. if (away > this.borderLimit) {
  74749. away = this.borderLimit;
  74750. }
  74751. var intensity = 1.0 - (away / this.borderLimit);
  74752. if (intensity < 0) {
  74753. return false;
  74754. }
  74755. if (intensity > 1.0) {
  74756. intensity = 1.0;
  74757. }
  74758. if (this.viewportBorder > 0) {
  74759. globalViewport.x += this.viewportBorder;
  74760. globalViewport.y += this.viewportBorder;
  74761. globalViewport.width -= this.viewportBorder * 2;
  74762. globalViewport.height -= this.viewportBorder * 2;
  74763. this._positionX -= this.viewportBorder;
  74764. this._positionY -= this.viewportBorder;
  74765. }
  74766. // Position
  74767. var centerX = globalViewport.x + globalViewport.width / 2;
  74768. var centerY = globalViewport.y + globalViewport.height / 2;
  74769. var distX = centerX - this._positionX;
  74770. var distY = centerY - this._positionY;
  74771. // Effects
  74772. engine.enableEffect(this._effect);
  74773. engine.setState(false);
  74774. engine.setDepthBuffer(false);
  74775. // VBOs
  74776. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  74777. // Flares
  74778. for (var index = 0; index < this.lensFlares.length; index++) {
  74779. var flare = this.lensFlares[index];
  74780. engine.setAlphaMode(flare.alphaMode);
  74781. var x = centerX - (distX * flare.position);
  74782. var y = centerY - (distY * flare.position);
  74783. var cw = flare.size;
  74784. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  74785. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  74786. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  74787. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  74788. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  74789. // Texture
  74790. this._effect.setTexture("textureSampler", flare.texture);
  74791. // Color
  74792. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  74793. // Draw order
  74794. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  74795. }
  74796. engine.setDepthBuffer(true);
  74797. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  74798. return true;
  74799. };
  74800. LensFlareSystem.prototype.dispose = function () {
  74801. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74802. if (vertexBuffer) {
  74803. vertexBuffer.dispose();
  74804. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  74805. }
  74806. if (this._indexBuffer) {
  74807. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  74808. this._indexBuffer = null;
  74809. }
  74810. while (this.lensFlares.length) {
  74811. this.lensFlares[0].dispose();
  74812. }
  74813. // Remove from scene
  74814. var index = this._scene.lensFlareSystems.indexOf(this);
  74815. this._scene.lensFlareSystems.splice(index, 1);
  74816. };
  74817. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  74818. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  74819. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  74820. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  74821. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  74822. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  74823. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  74824. var parsedFlare = parsedLensFlareSystem.flares[index];
  74825. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  74826. }
  74827. return lensFlareSystem;
  74828. };
  74829. LensFlareSystem.prototype.serialize = function () {
  74830. var serializationObject = {};
  74831. serializationObject.id = this.id;
  74832. serializationObject.name = this.name;
  74833. serializationObject.emitterId = this.getEmitter().id;
  74834. serializationObject.borderLimit = this.borderLimit;
  74835. serializationObject.flares = [];
  74836. for (var index = 0; index < this.lensFlares.length; index++) {
  74837. var flare = this.lensFlares[index];
  74838. serializationObject.flares.push({
  74839. size: flare.size,
  74840. position: flare.position,
  74841. color: flare.color.asArray(),
  74842. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  74843. });
  74844. }
  74845. return serializationObject;
  74846. };
  74847. return LensFlareSystem;
  74848. }());
  74849. BABYLON.LensFlareSystem = LensFlareSystem;
  74850. })(BABYLON || (BABYLON = {}));
  74851. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  74852. var BABYLON;
  74853. (function (BABYLON) {
  74854. /**
  74855. * This is a holder class for the physics joint created by the physics plugin.
  74856. * It holds a set of functions to control the underlying joint.
  74857. */
  74858. var PhysicsJoint = /** @class */ (function () {
  74859. function PhysicsJoint(type, jointData) {
  74860. this.type = type;
  74861. this.jointData = jointData;
  74862. jointData.nativeParams = jointData.nativeParams || {};
  74863. }
  74864. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  74865. get: function () {
  74866. return this._physicsJoint;
  74867. },
  74868. set: function (newJoint) {
  74869. if (this._physicsJoint) {
  74870. //remove from the wolrd
  74871. }
  74872. this._physicsJoint = newJoint;
  74873. },
  74874. enumerable: true,
  74875. configurable: true
  74876. });
  74877. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  74878. set: function (physicsPlugin) {
  74879. this._physicsPlugin = physicsPlugin;
  74880. },
  74881. enumerable: true,
  74882. configurable: true
  74883. });
  74884. /**
  74885. * Execute a function that is physics-plugin specific.
  74886. * @param {Function} func the function that will be executed.
  74887. * It accepts two parameters: the physics world and the physics joint.
  74888. */
  74889. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  74890. func(this._physicsPlugin.world, this._physicsJoint);
  74891. };
  74892. //TODO check if the native joints are the same
  74893. //Joint Types
  74894. PhysicsJoint.DistanceJoint = 0;
  74895. PhysicsJoint.HingeJoint = 1;
  74896. PhysicsJoint.BallAndSocketJoint = 2;
  74897. PhysicsJoint.WheelJoint = 3;
  74898. PhysicsJoint.SliderJoint = 4;
  74899. //OIMO
  74900. PhysicsJoint.PrismaticJoint = 5;
  74901. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  74902. PhysicsJoint.UniversalJoint = 6;
  74903. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  74904. //Cannon
  74905. //Similar to a Ball-Joint. Different in params
  74906. PhysicsJoint.PointToPointJoint = 8;
  74907. //Cannon only at the moment
  74908. PhysicsJoint.SpringJoint = 9;
  74909. PhysicsJoint.LockJoint = 10;
  74910. return PhysicsJoint;
  74911. }());
  74912. BABYLON.PhysicsJoint = PhysicsJoint;
  74913. /**
  74914. * A class representing a physics distance joint.
  74915. */
  74916. var DistanceJoint = /** @class */ (function (_super) {
  74917. __extends(DistanceJoint, _super);
  74918. function DistanceJoint(jointData) {
  74919. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  74920. }
  74921. /**
  74922. * Update the predefined distance.
  74923. */
  74924. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  74925. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  74926. };
  74927. return DistanceJoint;
  74928. }(PhysicsJoint));
  74929. BABYLON.DistanceJoint = DistanceJoint;
  74930. var MotorEnabledJoint = /** @class */ (function (_super) {
  74931. __extends(MotorEnabledJoint, _super);
  74932. function MotorEnabledJoint(type, jointData) {
  74933. return _super.call(this, type, jointData) || this;
  74934. }
  74935. /**
  74936. * Set the motor values.
  74937. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74938. * @param {number} force the force to apply
  74939. * @param {number} maxForce max force for this motor.
  74940. */
  74941. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  74942. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  74943. };
  74944. /**
  74945. * Set the motor's limits.
  74946. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74947. */
  74948. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  74949. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  74950. };
  74951. return MotorEnabledJoint;
  74952. }(PhysicsJoint));
  74953. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  74954. /**
  74955. * This class represents a single hinge physics joint
  74956. */
  74957. var HingeJoint = /** @class */ (function (_super) {
  74958. __extends(HingeJoint, _super);
  74959. function HingeJoint(jointData) {
  74960. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  74961. }
  74962. /**
  74963. * Set the motor values.
  74964. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74965. * @param {number} force the force to apply
  74966. * @param {number} maxForce max force for this motor.
  74967. */
  74968. HingeJoint.prototype.setMotor = function (force, maxForce) {
  74969. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  74970. };
  74971. /**
  74972. * Set the motor's limits.
  74973. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74974. */
  74975. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  74976. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  74977. };
  74978. return HingeJoint;
  74979. }(MotorEnabledJoint));
  74980. BABYLON.HingeJoint = HingeJoint;
  74981. /**
  74982. * This class represents a dual hinge physics joint (same as wheel joint)
  74983. */
  74984. var Hinge2Joint = /** @class */ (function (_super) {
  74985. __extends(Hinge2Joint, _super);
  74986. function Hinge2Joint(jointData) {
  74987. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  74988. }
  74989. /**
  74990. * Set the motor values.
  74991. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74992. * @param {number} force the force to apply
  74993. * @param {number} maxForce max force for this motor.
  74994. * @param {motorIndex} the motor's index, 0 or 1.
  74995. */
  74996. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  74997. if (motorIndex === void 0) { motorIndex = 0; }
  74998. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  74999. };
  75000. /**
  75001. * Set the motor limits.
  75002. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75003. * @param {number} upperLimit the upper limit
  75004. * @param {number} lowerLimit lower limit
  75005. * @param {motorIndex} the motor's index, 0 or 1.
  75006. */
  75007. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  75008. if (motorIndex === void 0) { motorIndex = 0; }
  75009. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  75010. };
  75011. return Hinge2Joint;
  75012. }(MotorEnabledJoint));
  75013. BABYLON.Hinge2Joint = Hinge2Joint;
  75014. })(BABYLON || (BABYLON = {}));
  75015. //# sourceMappingURL=babylon.physicsJoint.js.map
  75016. var BABYLON;
  75017. (function (BABYLON) {
  75018. var PhysicsImpostor = /** @class */ (function () {
  75019. function PhysicsImpostor(object, type, _options, _scene) {
  75020. if (_options === void 0) { _options = { mass: 0 }; }
  75021. var _this = this;
  75022. this.object = object;
  75023. this.type = type;
  75024. this._options = _options;
  75025. this._scene = _scene;
  75026. this._bodyUpdateRequired = false;
  75027. this._onBeforePhysicsStepCallbacks = new Array();
  75028. this._onAfterPhysicsStepCallbacks = new Array();
  75029. this._onPhysicsCollideCallbacks = [];
  75030. this._deltaPosition = BABYLON.Vector3.Zero();
  75031. this._isDisposed = false;
  75032. //temp variables for parent rotation calculations
  75033. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  75034. this._tmpQuat = new BABYLON.Quaternion();
  75035. this._tmpQuat2 = new BABYLON.Quaternion();
  75036. /**
  75037. * this function is executed by the physics engine.
  75038. */
  75039. this.beforeStep = function () {
  75040. if (!_this._physicsEngine) {
  75041. return;
  75042. }
  75043. _this.object.translate(_this._deltaPosition, -1);
  75044. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  75045. _this.object.computeWorldMatrix(false);
  75046. if (_this.object.parent && _this.object.rotationQuaternion) {
  75047. _this.getParentsRotation();
  75048. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  75049. }
  75050. else {
  75051. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  75052. }
  75053. if (!_this._options.disableBidirectionalTransformation) {
  75054. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  75055. }
  75056. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  75057. func(_this);
  75058. });
  75059. };
  75060. /**
  75061. * this function is executed by the physics engine.
  75062. */
  75063. this.afterStep = function () {
  75064. if (!_this._physicsEngine) {
  75065. return;
  75066. }
  75067. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  75068. func(_this);
  75069. });
  75070. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  75071. // object has now its world rotation. needs to be converted to local.
  75072. if (_this.object.parent && _this.object.rotationQuaternion) {
  75073. _this.getParentsRotation();
  75074. _this._tmpQuat.conjugateInPlace();
  75075. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  75076. }
  75077. // take the position set and make it the absolute position of this object.
  75078. _this.object.setAbsolutePosition(_this.object.position);
  75079. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  75080. _this.object.translate(_this._deltaPosition, 1);
  75081. };
  75082. /**
  75083. * Legacy collision detection event support
  75084. */
  75085. this.onCollideEvent = null;
  75086. //event and body object due to cannon's event-based architecture.
  75087. this.onCollide = function (e) {
  75088. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  75089. return;
  75090. }
  75091. if (!_this._physicsEngine) {
  75092. return;
  75093. }
  75094. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  75095. if (otherImpostor) {
  75096. // Legacy collision detection event support
  75097. if (_this.onCollideEvent) {
  75098. _this.onCollideEvent(_this, otherImpostor);
  75099. }
  75100. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  75101. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  75102. }).forEach(function (obj) {
  75103. obj.callback(_this, otherImpostor);
  75104. });
  75105. }
  75106. };
  75107. //sanity check!
  75108. if (!this.object) {
  75109. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  75110. return;
  75111. }
  75112. //legacy support for old syntax.
  75113. if (!this._scene && object.getScene) {
  75114. this._scene = object.getScene();
  75115. }
  75116. if (!this._scene) {
  75117. return;
  75118. }
  75119. this._physicsEngine = this._scene.getPhysicsEngine();
  75120. if (!this._physicsEngine) {
  75121. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  75122. }
  75123. else {
  75124. //set the object's quaternion, if not set
  75125. if (!this.object.rotationQuaternion) {
  75126. if (this.object.rotation) {
  75127. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  75128. }
  75129. else {
  75130. this.object.rotationQuaternion = new BABYLON.Quaternion();
  75131. }
  75132. }
  75133. //default options params
  75134. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  75135. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  75136. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  75137. this._joints = [];
  75138. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  75139. if (!this.object.parent || this._options.ignoreParent) {
  75140. this._init();
  75141. }
  75142. else if (this.object.parent.physicsImpostor) {
  75143. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  75144. }
  75145. }
  75146. }
  75147. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  75148. get: function () {
  75149. return this._isDisposed;
  75150. },
  75151. enumerable: true,
  75152. configurable: true
  75153. });
  75154. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  75155. get: function () {
  75156. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  75157. },
  75158. set: function (value) {
  75159. this.setMass(value);
  75160. },
  75161. enumerable: true,
  75162. configurable: true
  75163. });
  75164. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  75165. get: function () {
  75166. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  75167. },
  75168. set: function (value) {
  75169. if (!this._physicsEngine) {
  75170. return;
  75171. }
  75172. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  75173. },
  75174. enumerable: true,
  75175. configurable: true
  75176. });
  75177. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  75178. get: function () {
  75179. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  75180. },
  75181. set: function (value) {
  75182. if (!this._physicsEngine) {
  75183. return;
  75184. }
  75185. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  75186. },
  75187. enumerable: true,
  75188. configurable: true
  75189. });
  75190. /**
  75191. * This function will completly initialize this impostor.
  75192. * It will create a new body - but only if this mesh has no parent.
  75193. * If it has, this impostor will not be used other than to define the impostor
  75194. * of the child mesh.
  75195. */
  75196. PhysicsImpostor.prototype._init = function () {
  75197. if (!this._physicsEngine) {
  75198. return;
  75199. }
  75200. this._physicsEngine.removeImpostor(this);
  75201. this.physicsBody = null;
  75202. this._parent = this._parent || this._getPhysicsParent();
  75203. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  75204. this._physicsEngine.addImpostor(this);
  75205. }
  75206. };
  75207. PhysicsImpostor.prototype._getPhysicsParent = function () {
  75208. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  75209. var parentMesh = this.object.parent;
  75210. return parentMesh.physicsImpostor;
  75211. }
  75212. return null;
  75213. };
  75214. /**
  75215. * Should a new body be generated.
  75216. */
  75217. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  75218. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  75219. };
  75220. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  75221. this.forceUpdate();
  75222. };
  75223. /**
  75224. * Force a regeneration of this or the parent's impostor's body.
  75225. * Use under cautious - This will remove all joints already implemented.
  75226. */
  75227. PhysicsImpostor.prototype.forceUpdate = function () {
  75228. this._init();
  75229. if (this.parent && !this._options.ignoreParent) {
  75230. this.parent.forceUpdate();
  75231. }
  75232. };
  75233. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  75234. /*public get mesh(): AbstractMesh {
  75235. return this._mesh;
  75236. }*/
  75237. /**
  75238. * Gets the body that holds this impostor. Either its own, or its parent.
  75239. */
  75240. get: function () {
  75241. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  75242. },
  75243. /**
  75244. * Set the physics body. Used mainly by the physics engine/plugin
  75245. */
  75246. set: function (physicsBody) {
  75247. if (this._physicsBody && this._physicsEngine) {
  75248. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  75249. }
  75250. this._physicsBody = physicsBody;
  75251. this.resetUpdateFlags();
  75252. },
  75253. enumerable: true,
  75254. configurable: true
  75255. });
  75256. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  75257. get: function () {
  75258. return !this._options.ignoreParent && this._parent ? this._parent : null;
  75259. },
  75260. set: function (value) {
  75261. this._parent = value;
  75262. },
  75263. enumerable: true,
  75264. configurable: true
  75265. });
  75266. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  75267. this._bodyUpdateRequired = false;
  75268. };
  75269. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  75270. if (this.object.getBoundingInfo) {
  75271. var q = this.object.rotationQuaternion;
  75272. //reset rotation
  75273. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  75274. //calculate the world matrix with no rotation
  75275. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  75276. var boundingInfo = this.object.getBoundingInfo();
  75277. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  75278. //bring back the rotation
  75279. this.object.rotationQuaternion = q;
  75280. //calculate the world matrix with the new rotation
  75281. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  75282. return size;
  75283. }
  75284. else {
  75285. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  75286. }
  75287. };
  75288. PhysicsImpostor.prototype.getObjectCenter = function () {
  75289. if (this.object.getBoundingInfo) {
  75290. var boundingInfo = this.object.getBoundingInfo();
  75291. return boundingInfo.boundingBox.centerWorld;
  75292. }
  75293. else {
  75294. return this.object.position;
  75295. }
  75296. };
  75297. /**
  75298. * Get a specific parametes from the options parameter.
  75299. */
  75300. PhysicsImpostor.prototype.getParam = function (paramName) {
  75301. return this._options[paramName];
  75302. };
  75303. /**
  75304. * Sets a specific parameter in the options given to the physics plugin
  75305. */
  75306. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  75307. this._options[paramName] = value;
  75308. this._bodyUpdateRequired = true;
  75309. };
  75310. /**
  75311. * Specifically change the body's mass option. Won't recreate the physics body object
  75312. */
  75313. PhysicsImpostor.prototype.setMass = function (mass) {
  75314. if (this.getParam("mass") !== mass) {
  75315. this.setParam("mass", mass);
  75316. }
  75317. if (this._physicsEngine) {
  75318. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  75319. }
  75320. };
  75321. PhysicsImpostor.prototype.getLinearVelocity = function () {
  75322. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  75323. };
  75324. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  75325. if (this._physicsEngine) {
  75326. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  75327. }
  75328. };
  75329. PhysicsImpostor.prototype.getAngularVelocity = function () {
  75330. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  75331. };
  75332. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  75333. if (this._physicsEngine) {
  75334. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  75335. }
  75336. };
  75337. /**
  75338. * Execute a function with the physics plugin native code.
  75339. * Provide a function the will have two variables - the world object and the physics body object.
  75340. */
  75341. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  75342. if (this._physicsEngine) {
  75343. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  75344. }
  75345. };
  75346. /**
  75347. * Register a function that will be executed before the physics world is stepping forward.
  75348. */
  75349. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  75350. this._onBeforePhysicsStepCallbacks.push(func);
  75351. };
  75352. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  75353. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  75354. if (index > -1) {
  75355. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  75356. }
  75357. else {
  75358. BABYLON.Tools.Warn("Function to remove was not found");
  75359. }
  75360. };
  75361. /**
  75362. * Register a function that will be executed after the physics step
  75363. */
  75364. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  75365. this._onAfterPhysicsStepCallbacks.push(func);
  75366. };
  75367. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  75368. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  75369. if (index > -1) {
  75370. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  75371. }
  75372. else {
  75373. BABYLON.Tools.Warn("Function to remove was not found");
  75374. }
  75375. };
  75376. /**
  75377. * register a function that will be executed when this impostor collides against a different body.
  75378. */
  75379. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  75380. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  75381. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  75382. };
  75383. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  75384. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  75385. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  75386. if (index > -1) {
  75387. this._onPhysicsCollideCallbacks.splice(index, 1);
  75388. }
  75389. else {
  75390. BABYLON.Tools.Warn("Function to remove was not found");
  75391. }
  75392. };
  75393. PhysicsImpostor.prototype.getParentsRotation = function () {
  75394. var parent = this.object.parent;
  75395. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  75396. while (parent) {
  75397. if (parent.rotationQuaternion) {
  75398. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  75399. }
  75400. else {
  75401. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  75402. }
  75403. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  75404. parent = parent.parent;
  75405. }
  75406. return this._tmpQuat;
  75407. };
  75408. /**
  75409. * Apply a force
  75410. */
  75411. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  75412. if (this._physicsEngine) {
  75413. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  75414. }
  75415. return this;
  75416. };
  75417. /**
  75418. * Apply an impulse
  75419. */
  75420. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  75421. if (this._physicsEngine) {
  75422. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  75423. }
  75424. return this;
  75425. };
  75426. /**
  75427. * A help function to create a joint.
  75428. */
  75429. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  75430. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  75431. this.addJoint(otherImpostor, joint);
  75432. return this;
  75433. };
  75434. /**
  75435. * Add a joint to this impostor with a different impostor.
  75436. */
  75437. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  75438. this._joints.push({
  75439. otherImpostor: otherImpostor,
  75440. joint: joint
  75441. });
  75442. if (this._physicsEngine) {
  75443. this._physicsEngine.addJoint(this, otherImpostor, joint);
  75444. }
  75445. return this;
  75446. };
  75447. /**
  75448. * Will keep this body still, in a sleep mode.
  75449. */
  75450. PhysicsImpostor.prototype.sleep = function () {
  75451. if (this._physicsEngine) {
  75452. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  75453. }
  75454. return this;
  75455. };
  75456. /**
  75457. * Wake the body up.
  75458. */
  75459. PhysicsImpostor.prototype.wakeUp = function () {
  75460. if (this._physicsEngine) {
  75461. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  75462. }
  75463. return this;
  75464. };
  75465. PhysicsImpostor.prototype.clone = function (newObject) {
  75466. if (!newObject)
  75467. return null;
  75468. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  75469. };
  75470. PhysicsImpostor.prototype.dispose = function () {
  75471. var _this = this;
  75472. //no dispose if no physics engine is available.
  75473. if (!this._physicsEngine) {
  75474. return;
  75475. }
  75476. this._joints.forEach(function (j) {
  75477. if (_this._physicsEngine) {
  75478. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  75479. }
  75480. });
  75481. //dispose the physics body
  75482. this._physicsEngine.removeImpostor(this);
  75483. if (this.parent) {
  75484. this.parent.forceUpdate();
  75485. }
  75486. else {
  75487. /*this._object.getChildMeshes().forEach(function(mesh) {
  75488. if (mesh.physicsImpostor) {
  75489. if (disposeChildren) {
  75490. mesh.physicsImpostor.dispose();
  75491. mesh.physicsImpostor = null;
  75492. }
  75493. }
  75494. })*/
  75495. }
  75496. this._isDisposed = true;
  75497. };
  75498. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  75499. this._deltaPosition.copyFrom(position);
  75500. };
  75501. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  75502. if (!this._deltaRotation) {
  75503. this._deltaRotation = new BABYLON.Quaternion();
  75504. }
  75505. this._deltaRotation.copyFrom(rotation);
  75506. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  75507. };
  75508. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  75509. if (this._physicsEngine) {
  75510. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  75511. }
  75512. return this;
  75513. };
  75514. PhysicsImpostor.prototype.getRadius = function () {
  75515. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  75516. };
  75517. /**
  75518. * Sync a bone with this impostor
  75519. * @param bone The bone to sync to the impostor.
  75520. * @param boneMesh The mesh that the bone is influencing.
  75521. * @param jointPivot The pivot of the joint / bone in local space.
  75522. * @param distToJoint Optional distance from the impostor to the joint.
  75523. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  75524. */
  75525. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  75526. var tempVec = PhysicsImpostor._tmpVecs[0];
  75527. var mesh = this.object;
  75528. if (mesh.rotationQuaternion) {
  75529. if (adjustRotation) {
  75530. var tempQuat = PhysicsImpostor._tmpQuat;
  75531. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  75532. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  75533. }
  75534. else {
  75535. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  75536. }
  75537. }
  75538. tempVec.x = 0;
  75539. tempVec.y = 0;
  75540. tempVec.z = 0;
  75541. if (jointPivot) {
  75542. tempVec.x = jointPivot.x;
  75543. tempVec.y = jointPivot.y;
  75544. tempVec.z = jointPivot.z;
  75545. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  75546. if (distToJoint === undefined || distToJoint === null) {
  75547. distToJoint = jointPivot.length();
  75548. }
  75549. tempVec.x *= distToJoint;
  75550. tempVec.y *= distToJoint;
  75551. tempVec.z *= distToJoint;
  75552. }
  75553. if (bone.getParent()) {
  75554. tempVec.addInPlace(mesh.getAbsolutePosition());
  75555. bone.setAbsolutePosition(tempVec, boneMesh);
  75556. }
  75557. else {
  75558. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  75559. boneMesh.position.x -= tempVec.x;
  75560. boneMesh.position.y -= tempVec.y;
  75561. boneMesh.position.z -= tempVec.z;
  75562. }
  75563. };
  75564. /**
  75565. * Sync impostor to a bone
  75566. * @param bone The bone that the impostor will be synced to.
  75567. * @param boneMesh The mesh that the bone is influencing.
  75568. * @param jointPivot The pivot of the joint / bone in local space.
  75569. * @param distToJoint Optional distance from the impostor to the joint.
  75570. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  75571. * @param boneAxis Optional vector3 axis the bone is aligned with
  75572. */
  75573. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  75574. var mesh = this.object;
  75575. if (mesh.rotationQuaternion) {
  75576. if (adjustRotation) {
  75577. var tempQuat = PhysicsImpostor._tmpQuat;
  75578. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  75579. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  75580. }
  75581. else {
  75582. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  75583. }
  75584. }
  75585. var pos = PhysicsImpostor._tmpVecs[0];
  75586. var boneDir = PhysicsImpostor._tmpVecs[1];
  75587. if (!boneAxis) {
  75588. boneAxis = PhysicsImpostor._tmpVecs[2];
  75589. boneAxis.x = 0;
  75590. boneAxis.y = 1;
  75591. boneAxis.z = 0;
  75592. }
  75593. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  75594. bone.getAbsolutePositionToRef(boneMesh, pos);
  75595. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  75596. distToJoint = jointPivot.length();
  75597. }
  75598. if (distToJoint !== undefined && distToJoint !== null) {
  75599. pos.x += boneDir.x * distToJoint;
  75600. pos.y += boneDir.y * distToJoint;
  75601. pos.z += boneDir.z * distToJoint;
  75602. }
  75603. mesh.setAbsolutePosition(pos);
  75604. };
  75605. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  75606. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  75607. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  75608. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  75609. //Impostor types
  75610. PhysicsImpostor.NoImpostor = 0;
  75611. PhysicsImpostor.SphereImpostor = 1;
  75612. PhysicsImpostor.BoxImpostor = 2;
  75613. PhysicsImpostor.PlaneImpostor = 3;
  75614. PhysicsImpostor.MeshImpostor = 4;
  75615. PhysicsImpostor.CylinderImpostor = 7;
  75616. PhysicsImpostor.ParticleImpostor = 8;
  75617. PhysicsImpostor.HeightmapImpostor = 9;
  75618. return PhysicsImpostor;
  75619. }());
  75620. BABYLON.PhysicsImpostor = PhysicsImpostor;
  75621. })(BABYLON || (BABYLON = {}));
  75622. //# sourceMappingURL=babylon.physicsImpostor.js.map
  75623. var BABYLON;
  75624. (function (BABYLON) {
  75625. var PhysicsEngine = /** @class */ (function () {
  75626. function PhysicsEngine(gravity, _physicsPlugin) {
  75627. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  75628. this._physicsPlugin = _physicsPlugin;
  75629. //new methods and parameters
  75630. this._impostors = [];
  75631. this._joints = [];
  75632. if (!this._physicsPlugin.isSupported()) {
  75633. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  75634. + "Please make sure it is included.");
  75635. }
  75636. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  75637. this.setGravity(gravity);
  75638. this.setTimeStep();
  75639. }
  75640. PhysicsEngine.prototype.setGravity = function (gravity) {
  75641. this.gravity = gravity;
  75642. this._physicsPlugin.setGravity(this.gravity);
  75643. };
  75644. /**
  75645. * Set the time step of the physics engine.
  75646. * default is 1/60.
  75647. * To slow it down, enter 1/600 for example.
  75648. * To speed it up, 1/30
  75649. * @param {number} newTimeStep the new timestep to apply to this world.
  75650. */
  75651. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  75652. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  75653. this._physicsPlugin.setTimeStep(newTimeStep);
  75654. };
  75655. /**
  75656. * Get the time step of the physics engine.
  75657. */
  75658. PhysicsEngine.prototype.getTimeStep = function () {
  75659. return this._physicsPlugin.getTimeStep();
  75660. };
  75661. PhysicsEngine.prototype.dispose = function () {
  75662. this._impostors.forEach(function (impostor) {
  75663. impostor.dispose();
  75664. });
  75665. this._physicsPlugin.dispose();
  75666. };
  75667. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  75668. return this._physicsPlugin.name;
  75669. };
  75670. /**
  75671. * Adding a new impostor for the impostor tracking.
  75672. * This will be done by the impostor itself.
  75673. * @param {PhysicsImpostor} impostor the impostor to add
  75674. */
  75675. PhysicsEngine.prototype.addImpostor = function (impostor) {
  75676. impostor.uniqueId = this._impostors.push(impostor);
  75677. //if no parent, generate the body
  75678. if (!impostor.parent) {
  75679. this._physicsPlugin.generatePhysicsBody(impostor);
  75680. }
  75681. };
  75682. /**
  75683. * Remove an impostor from the engine.
  75684. * This impostor and its mesh will not longer be updated by the physics engine.
  75685. * @param {PhysicsImpostor} impostor the impostor to remove
  75686. */
  75687. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  75688. var index = this._impostors.indexOf(impostor);
  75689. if (index > -1) {
  75690. var removed = this._impostors.splice(index, 1);
  75691. //Is it needed?
  75692. if (removed.length) {
  75693. //this will also remove it from the world.
  75694. removed[0].physicsBody = null;
  75695. }
  75696. }
  75697. };
  75698. /**
  75699. * Add a joint to the physics engine
  75700. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  75701. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  75702. * @param {PhysicsJoint} the joint that will connect both impostors.
  75703. */
  75704. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  75705. var impostorJoint = {
  75706. mainImpostor: mainImpostor,
  75707. connectedImpostor: connectedImpostor,
  75708. joint: joint
  75709. };
  75710. joint.physicsPlugin = this._physicsPlugin;
  75711. this._joints.push(impostorJoint);
  75712. this._physicsPlugin.generateJoint(impostorJoint);
  75713. };
  75714. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  75715. var matchingJoints = this._joints.filter(function (impostorJoint) {
  75716. return (impostorJoint.connectedImpostor === connectedImpostor
  75717. && impostorJoint.joint === joint
  75718. && impostorJoint.mainImpostor === mainImpostor);
  75719. });
  75720. if (matchingJoints.length) {
  75721. this._physicsPlugin.removeJoint(matchingJoints[0]);
  75722. //TODO remove it from the list as well
  75723. }
  75724. };
  75725. /**
  75726. * Called by the scene. no need to call it.
  75727. */
  75728. PhysicsEngine.prototype._step = function (delta) {
  75729. var _this = this;
  75730. //check if any mesh has no body / requires an update
  75731. this._impostors.forEach(function (impostor) {
  75732. if (impostor.isBodyInitRequired()) {
  75733. _this._physicsPlugin.generatePhysicsBody(impostor);
  75734. }
  75735. });
  75736. if (delta > 0.1) {
  75737. delta = 0.1;
  75738. }
  75739. else if (delta <= 0) {
  75740. delta = 1.0 / 60.0;
  75741. }
  75742. this._physicsPlugin.executeStep(delta, this._impostors);
  75743. };
  75744. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  75745. return this._physicsPlugin;
  75746. };
  75747. PhysicsEngine.prototype.getImpostors = function () {
  75748. return this._impostors;
  75749. };
  75750. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  75751. for (var i = 0; i < this._impostors.length; ++i) {
  75752. if (this._impostors[i].object === object) {
  75753. return this._impostors[i];
  75754. }
  75755. }
  75756. return null;
  75757. };
  75758. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  75759. for (var i = 0; i < this._impostors.length; ++i) {
  75760. if (this._impostors[i].physicsBody === body) {
  75761. return this._impostors[i];
  75762. }
  75763. }
  75764. return null;
  75765. };
  75766. // Statics
  75767. PhysicsEngine.Epsilon = 0.001;
  75768. return PhysicsEngine;
  75769. }());
  75770. BABYLON.PhysicsEngine = PhysicsEngine;
  75771. })(BABYLON || (BABYLON = {}));
  75772. //# sourceMappingURL=babylon.physicsEngine.js.map
  75773. var BABYLON;
  75774. (function (BABYLON) {
  75775. var PhysicsHelper = /** @class */ (function () {
  75776. function PhysicsHelper(scene) {
  75777. this._scene = scene;
  75778. this._physicsEngine = this._scene.getPhysicsEngine();
  75779. if (!this._physicsEngine) {
  75780. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  75781. }
  75782. }
  75783. /**
  75784. * @param {Vector3} origin the origin of the explosion
  75785. * @param {number} radius the explosion radius
  75786. * @param {number} strength the explosion strength
  75787. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  75788. */
  75789. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  75790. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75791. if (!this._physicsEngine) {
  75792. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  75793. return null;
  75794. }
  75795. var impostors = this._physicsEngine.getImpostors();
  75796. if (impostors.length === 0) {
  75797. return null;
  75798. }
  75799. var event = new PhysicsRadialExplosionEvent(this._scene);
  75800. impostors.forEach(function (impostor) {
  75801. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  75802. if (!impostorForceAndContactPoint) {
  75803. return;
  75804. }
  75805. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75806. });
  75807. event.dispose(false);
  75808. return event;
  75809. };
  75810. /**
  75811. * @param {Vector3} origin the origin of the explosion
  75812. * @param {number} radius the explosion radius
  75813. * @param {number} strength the explosion strength
  75814. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  75815. */
  75816. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  75817. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75818. if (!this._physicsEngine) {
  75819. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75820. return null;
  75821. }
  75822. var impostors = this._physicsEngine.getImpostors();
  75823. if (impostors.length === 0) {
  75824. return null;
  75825. }
  75826. var event = new PhysicsRadialExplosionEvent(this._scene);
  75827. impostors.forEach(function (impostor) {
  75828. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  75829. if (!impostorForceAndContactPoint) {
  75830. return;
  75831. }
  75832. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75833. });
  75834. event.dispose(false);
  75835. return event;
  75836. };
  75837. /**
  75838. * @param {Vector3} origin the origin of the explosion
  75839. * @param {number} radius the explosion radius
  75840. * @param {number} strength the explosion strength
  75841. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  75842. */
  75843. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  75844. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75845. if (!this._physicsEngine) {
  75846. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75847. return null;
  75848. }
  75849. var impostors = this._physicsEngine.getImpostors();
  75850. if (impostors.length === 0) {
  75851. return null;
  75852. }
  75853. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  75854. event.dispose(false);
  75855. return event;
  75856. };
  75857. /**
  75858. * @param {Vector3} origin the origin of the updraft
  75859. * @param {number} radius the radius of the updraft
  75860. * @param {number} strength the strength of the updraft
  75861. * @param {number} height the height of the updraft
  75862. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  75863. */
  75864. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  75865. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  75866. if (!this._physicsEngine) {
  75867. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75868. return null;
  75869. }
  75870. if (this._physicsEngine.getImpostors().length === 0) {
  75871. return null;
  75872. }
  75873. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  75874. event.dispose(false);
  75875. return event;
  75876. };
  75877. /**
  75878. * @param {Vector3} origin the of the vortex
  75879. * @param {number} radius the radius of the vortex
  75880. * @param {number} strength the strength of the vortex
  75881. * @param {number} height the height of the vortex
  75882. */
  75883. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  75884. if (!this._physicsEngine) {
  75885. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75886. return null;
  75887. }
  75888. if (this._physicsEngine.getImpostors().length === 0) {
  75889. return null;
  75890. }
  75891. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  75892. event.dispose(false);
  75893. return event;
  75894. };
  75895. return PhysicsHelper;
  75896. }());
  75897. BABYLON.PhysicsHelper = PhysicsHelper;
  75898. /***** Radial explosion *****/
  75899. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  75900. function PhysicsRadialExplosionEvent(scene) {
  75901. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  75902. this._rays = [];
  75903. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  75904. this._scene = scene;
  75905. }
  75906. /**
  75907. * Returns the data related to the radial explosion event (sphere & rays).
  75908. * @returns {PhysicsRadialExplosionEventData}
  75909. */
  75910. PhysicsRadialExplosionEvent.prototype.getData = function () {
  75911. this._dataFetched = true;
  75912. return {
  75913. sphere: this._sphere,
  75914. rays: this._rays,
  75915. };
  75916. };
  75917. /**
  75918. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  75919. * @param impostor
  75920. * @param {Vector3} origin the origin of the explosion
  75921. * @param {number} radius the explosion radius
  75922. * @param {number} strength the explosion strength
  75923. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  75924. * @returns {Nullable<PhysicsForceAndContactPoint>}
  75925. */
  75926. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  75927. if (impostor.mass === 0) {
  75928. return null;
  75929. }
  75930. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  75931. return null;
  75932. }
  75933. if (impostor.object.getClassName() !== 'Mesh') {
  75934. return null;
  75935. }
  75936. var impostorObject = impostor.object;
  75937. var impostorObjectCenter = impostor.getObjectCenter();
  75938. var direction = impostorObjectCenter.subtract(origin);
  75939. var ray = new BABYLON.Ray(origin, direction, radius);
  75940. this._rays.push(ray);
  75941. var hit = ray.intersectsMesh(impostorObject);
  75942. var contactPoint = hit.pickedPoint;
  75943. if (!contactPoint) {
  75944. return null;
  75945. }
  75946. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  75947. if (distanceFromOrigin > radius) {
  75948. return null;
  75949. }
  75950. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  75951. ? strength
  75952. : strength * (1 - (distanceFromOrigin / radius));
  75953. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  75954. return { force: force, contactPoint: contactPoint };
  75955. };
  75956. /**
  75957. * Disposes the sphere.
  75958. * @param {bolean} force
  75959. */
  75960. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  75961. var _this = this;
  75962. if (force === void 0) { force = true; }
  75963. if (force) {
  75964. this._sphere.dispose();
  75965. }
  75966. else {
  75967. setTimeout(function () {
  75968. if (!_this._dataFetched) {
  75969. _this._sphere.dispose();
  75970. }
  75971. }, 0);
  75972. }
  75973. };
  75974. /*** Helpers ***/
  75975. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  75976. if (!this._sphere) {
  75977. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  75978. this._sphere.isVisible = false;
  75979. }
  75980. };
  75981. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  75982. var impostorObject = impostor.object;
  75983. this._prepareSphere();
  75984. this._sphere.position = origin;
  75985. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  75986. this._sphere._updateBoundingInfo();
  75987. this._sphere.computeWorldMatrix(true);
  75988. return this._sphere.intersectsMesh(impostorObject, true);
  75989. };
  75990. return PhysicsRadialExplosionEvent;
  75991. }());
  75992. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  75993. /***** Gravitational Field *****/
  75994. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  75995. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  75996. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75997. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  75998. this._physicsHelper = physicsHelper;
  75999. this._scene = scene;
  76000. this._origin = origin;
  76001. this._radius = radius;
  76002. this._strength = strength;
  76003. this._falloff = falloff;
  76004. this._tickCallback = this._tick.bind(this);
  76005. }
  76006. /**
  76007. * Returns the data related to the gravitational field event (sphere).
  76008. * @returns {PhysicsGravitationalFieldEventData}
  76009. */
  76010. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  76011. this._dataFetched = true;
  76012. return {
  76013. sphere: this._sphere,
  76014. };
  76015. };
  76016. /**
  76017. * Enables the gravitational field.
  76018. */
  76019. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  76020. this._tickCallback.call(this);
  76021. this._scene.registerBeforeRender(this._tickCallback);
  76022. };
  76023. /**
  76024. * Disables the gravitational field.
  76025. */
  76026. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  76027. this._scene.unregisterBeforeRender(this._tickCallback);
  76028. };
  76029. /**
  76030. * Disposes the sphere.
  76031. * @param {bolean} force
  76032. */
  76033. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  76034. var _this = this;
  76035. if (force === void 0) { force = true; }
  76036. if (force) {
  76037. this._sphere.dispose();
  76038. }
  76039. else {
  76040. setTimeout(function () {
  76041. if (!_this._dataFetched) {
  76042. _this._sphere.dispose();
  76043. }
  76044. }, 0);
  76045. }
  76046. };
  76047. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  76048. // Since the params won't change, we fetch the event only once
  76049. if (this._sphere) {
  76050. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  76051. }
  76052. else {
  76053. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  76054. if (radialExplosionEvent) {
  76055. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  76056. }
  76057. }
  76058. };
  76059. return PhysicsGravitationalFieldEvent;
  76060. }());
  76061. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  76062. /***** Updraft *****/
  76063. var PhysicsUpdraftEvent = /** @class */ (function () {
  76064. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  76065. this._scene = _scene;
  76066. this._origin = _origin;
  76067. this._radius = _radius;
  76068. this._strength = _strength;
  76069. this._height = _height;
  76070. this._updraftMode = _updraftMode;
  76071. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  76072. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  76073. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  76074. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  76075. this._physicsEngine = this._scene.getPhysicsEngine();
  76076. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  76077. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  76078. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  76079. this._originDirection = this._origin.subtract(this._originTop).normalize();
  76080. }
  76081. this._tickCallback = this._tick.bind(this);
  76082. }
  76083. /**
  76084. * Returns the data related to the updraft event (cylinder).
  76085. * @returns {PhysicsUpdraftEventData}
  76086. */
  76087. PhysicsUpdraftEvent.prototype.getData = function () {
  76088. this._dataFetched = true;
  76089. return {
  76090. cylinder: this._cylinder,
  76091. };
  76092. };
  76093. /**
  76094. * Enables the updraft.
  76095. */
  76096. PhysicsUpdraftEvent.prototype.enable = function () {
  76097. this._tickCallback.call(this);
  76098. this._scene.registerBeforeRender(this._tickCallback);
  76099. };
  76100. /**
  76101. * Disables the cortex.
  76102. */
  76103. PhysicsUpdraftEvent.prototype.disable = function () {
  76104. this._scene.unregisterBeforeRender(this._tickCallback);
  76105. };
  76106. /**
  76107. * Disposes the sphere.
  76108. * @param {bolean} force
  76109. */
  76110. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  76111. var _this = this;
  76112. if (force === void 0) { force = true; }
  76113. if (force) {
  76114. this._cylinder.dispose();
  76115. }
  76116. else {
  76117. setTimeout(function () {
  76118. if (!_this._dataFetched) {
  76119. _this._cylinder.dispose();
  76120. }
  76121. }, 0);
  76122. }
  76123. };
  76124. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  76125. if (impostor.mass === 0) {
  76126. return null;
  76127. }
  76128. if (!this._intersectsWithCylinder(impostor)) {
  76129. return null;
  76130. }
  76131. var impostorObjectCenter = impostor.getObjectCenter();
  76132. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  76133. var direction = this._originDirection;
  76134. }
  76135. else {
  76136. var direction = impostorObjectCenter.subtract(this._originTop);
  76137. }
  76138. var multiplier = this._strength * -1;
  76139. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  76140. return { force: force, contactPoint: impostorObjectCenter };
  76141. };
  76142. PhysicsUpdraftEvent.prototype._tick = function () {
  76143. var _this = this;
  76144. this._physicsEngine.getImpostors().forEach(function (impostor) {
  76145. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  76146. if (!impostorForceAndContactPoint) {
  76147. return;
  76148. }
  76149. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76150. });
  76151. };
  76152. /*** Helpers ***/
  76153. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  76154. if (!this._cylinder) {
  76155. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  76156. height: this._height,
  76157. diameter: this._radius * 2,
  76158. }, this._scene);
  76159. this._cylinder.isVisible = false;
  76160. }
  76161. };
  76162. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  76163. var impostorObject = impostor.object;
  76164. this._prepareCylinder();
  76165. this._cylinder.position = this._cylinderPosition;
  76166. return this._cylinder.intersectsMesh(impostorObject, true);
  76167. };
  76168. return PhysicsUpdraftEvent;
  76169. }());
  76170. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  76171. /***** Vortex *****/
  76172. var PhysicsVortexEvent = /** @class */ (function () {
  76173. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  76174. this._scene = _scene;
  76175. this._origin = _origin;
  76176. this._radius = _radius;
  76177. this._strength = _strength;
  76178. this._height = _height;
  76179. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  76180. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  76181. this._updraftMultiplier = 0.02;
  76182. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  76183. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  76184. this._physicsEngine = this._scene.getPhysicsEngine();
  76185. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  76186. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  76187. this._tickCallback = this._tick.bind(this);
  76188. }
  76189. /**
  76190. * Returns the data related to the vortex event (cylinder).
  76191. * @returns {PhysicsVortexEventData}
  76192. */
  76193. PhysicsVortexEvent.prototype.getData = function () {
  76194. this._dataFetched = true;
  76195. return {
  76196. cylinder: this._cylinder,
  76197. };
  76198. };
  76199. /**
  76200. * Enables the vortex.
  76201. */
  76202. PhysicsVortexEvent.prototype.enable = function () {
  76203. this._tickCallback.call(this);
  76204. this._scene.registerBeforeRender(this._tickCallback);
  76205. };
  76206. /**
  76207. * Disables the cortex.
  76208. */
  76209. PhysicsVortexEvent.prototype.disable = function () {
  76210. this._scene.unregisterBeforeRender(this._tickCallback);
  76211. };
  76212. /**
  76213. * Disposes the sphere.
  76214. * @param {bolean} force
  76215. */
  76216. PhysicsVortexEvent.prototype.dispose = function (force) {
  76217. var _this = this;
  76218. if (force === void 0) { force = true; }
  76219. if (force) {
  76220. this._cylinder.dispose();
  76221. }
  76222. else {
  76223. setTimeout(function () {
  76224. if (!_this._dataFetched) {
  76225. _this._cylinder.dispose();
  76226. }
  76227. }, 0);
  76228. }
  76229. };
  76230. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  76231. if (impostor.mass === 0) {
  76232. return null;
  76233. }
  76234. if (!this._intersectsWithCylinder(impostor)) {
  76235. return null;
  76236. }
  76237. if (impostor.object.getClassName() !== 'Mesh') {
  76238. return null;
  76239. }
  76240. var impostorObject = impostor.object;
  76241. var impostorObjectCenter = impostor.getObjectCenter();
  76242. 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)
  76243. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  76244. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  76245. var hit = ray.intersectsMesh(impostorObject);
  76246. var contactPoint = hit.pickedPoint;
  76247. if (!contactPoint) {
  76248. return null;
  76249. }
  76250. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  76251. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  76252. var directionToOrigin = contactPoint.normalize();
  76253. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  76254. directionToOrigin = directionToOrigin.negate();
  76255. }
  76256. // TODO: find a more physically based solution
  76257. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  76258. var forceX = directionToOrigin.x * this._strength / 8;
  76259. var forceY = directionToOrigin.y * this._updraftMultiplier;
  76260. var forceZ = directionToOrigin.z * this._strength / 8;
  76261. }
  76262. else {
  76263. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  76264. var forceY = this._originTop.y * this._updraftMultiplier;
  76265. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  76266. }
  76267. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  76268. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  76269. return { force: force, contactPoint: impostorObjectCenter };
  76270. };
  76271. PhysicsVortexEvent.prototype._tick = function () {
  76272. var _this = this;
  76273. this._physicsEngine.getImpostors().forEach(function (impostor) {
  76274. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  76275. if (!impostorForceAndContactPoint) {
  76276. return;
  76277. }
  76278. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76279. });
  76280. };
  76281. /*** Helpers ***/
  76282. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  76283. if (!this._cylinder) {
  76284. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  76285. height: this._height,
  76286. diameter: this._radius * 2,
  76287. }, this._scene);
  76288. this._cylinder.isVisible = false;
  76289. }
  76290. };
  76291. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  76292. var impostorObject = impostor.object;
  76293. this._prepareCylinder();
  76294. this._cylinder.position = this._cylinderPosition;
  76295. return this._cylinder.intersectsMesh(impostorObject, true);
  76296. };
  76297. return PhysicsVortexEvent;
  76298. }());
  76299. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  76300. /***** Enums *****/
  76301. /**
  76302. * The strenght of the force in correspondence to the distance of the affected object
  76303. */
  76304. var PhysicsRadialImpulseFalloff;
  76305. (function (PhysicsRadialImpulseFalloff) {
  76306. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  76307. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  76308. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  76309. /**
  76310. * The strenght of the force in correspondence to the distance of the affected object
  76311. */
  76312. var PhysicsUpdraftMode;
  76313. (function (PhysicsUpdraftMode) {
  76314. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  76315. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  76316. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  76317. })(BABYLON || (BABYLON = {}));
  76318. //# sourceMappingURL=babylon.physicsHelper.js.map
  76319. var BABYLON;
  76320. (function (BABYLON) {
  76321. var CannonJSPlugin = /** @class */ (function () {
  76322. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  76323. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  76324. if (iterations === void 0) { iterations = 10; }
  76325. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  76326. this.name = "CannonJSPlugin";
  76327. this._physicsMaterials = new Array();
  76328. this._fixedTimeStep = 1 / 60;
  76329. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  76330. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  76331. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  76332. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  76333. this._tmpPosition = BABYLON.Vector3.Zero();
  76334. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  76335. this._tmpUnityRotation = new BABYLON.Quaternion();
  76336. if (!this.isSupported()) {
  76337. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  76338. return;
  76339. }
  76340. this._extendNamespace();
  76341. this.world = new this.BJSCANNON.World();
  76342. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  76343. this.world.solver.iterations = iterations;
  76344. }
  76345. CannonJSPlugin.prototype.setGravity = function (gravity) {
  76346. this.world.gravity.copy(gravity);
  76347. };
  76348. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  76349. this._fixedTimeStep = timeStep;
  76350. };
  76351. CannonJSPlugin.prototype.getTimeStep = function () {
  76352. return this._fixedTimeStep;
  76353. };
  76354. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  76355. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  76356. };
  76357. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  76358. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  76359. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  76360. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  76361. };
  76362. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  76363. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  76364. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  76365. impostor.physicsBody.applyForce(impulse, worldPoint);
  76366. };
  76367. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  76368. //parent-child relationship. Does this impostor has a parent impostor?
  76369. if (impostor.parent) {
  76370. if (impostor.physicsBody) {
  76371. this.removePhysicsBody(impostor);
  76372. //TODO is that needed?
  76373. impostor.forceUpdate();
  76374. }
  76375. return;
  76376. }
  76377. //should a new body be created for this impostor?
  76378. if (impostor.isBodyInitRequired()) {
  76379. var shape = this._createShape(impostor);
  76380. //unregister events, if body is being changed
  76381. var oldBody = impostor.physicsBody;
  76382. if (oldBody) {
  76383. this.removePhysicsBody(impostor);
  76384. }
  76385. //create the body and material
  76386. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  76387. var bodyCreationObject = {
  76388. mass: impostor.getParam("mass"),
  76389. material: material
  76390. };
  76391. // A simple extend, in case native options were used.
  76392. var nativeOptions = impostor.getParam("nativeOptions");
  76393. for (var key in nativeOptions) {
  76394. if (nativeOptions.hasOwnProperty(key)) {
  76395. bodyCreationObject[key] = nativeOptions[key];
  76396. }
  76397. }
  76398. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  76399. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  76400. this.world.addEventListener("preStep", impostor.beforeStep);
  76401. this.world.addEventListener("postStep", impostor.afterStep);
  76402. impostor.physicsBody.addShape(shape);
  76403. this.world.add(impostor.physicsBody);
  76404. //try to keep the body moving in the right direction by taking old properties.
  76405. //Should be tested!
  76406. if (oldBody) {
  76407. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  76408. impostor.physicsBody[param].copy(oldBody[param]);
  76409. });
  76410. }
  76411. this._processChildMeshes(impostor);
  76412. }
  76413. //now update the body's transformation
  76414. this._updatePhysicsBodyTransformation(impostor);
  76415. };
  76416. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  76417. var _this = this;
  76418. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  76419. var currentRotation = mainImpostor.object.rotationQuaternion;
  76420. if (meshChildren.length) {
  76421. var processMesh = function (localPosition, mesh) {
  76422. if (!currentRotation || !mesh.rotationQuaternion) {
  76423. return;
  76424. }
  76425. var childImpostor = mesh.getPhysicsImpostor();
  76426. if (childImpostor) {
  76427. var parent = childImpostor.parent;
  76428. if (parent !== mainImpostor) {
  76429. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  76430. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  76431. if (childImpostor.physicsBody) {
  76432. _this.removePhysicsBody(childImpostor);
  76433. childImpostor.physicsBody = null;
  76434. }
  76435. childImpostor.parent = mainImpostor;
  76436. childImpostor.resetUpdateFlags();
  76437. 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));
  76438. //Add the mass of the children.
  76439. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  76440. }
  76441. }
  76442. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  76443. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  76444. };
  76445. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  76446. }
  76447. };
  76448. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  76449. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  76450. this.world.removeEventListener("preStep", impostor.beforeStep);
  76451. this.world.removeEventListener("postStep", impostor.afterStep);
  76452. this.world.remove(impostor.physicsBody);
  76453. };
  76454. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  76455. var mainBody = impostorJoint.mainImpostor.physicsBody;
  76456. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  76457. if (!mainBody || !connectedBody) {
  76458. return;
  76459. }
  76460. var constraint;
  76461. var jointData = impostorJoint.joint.jointData;
  76462. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  76463. var constraintData = {
  76464. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  76465. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  76466. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  76467. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  76468. maxForce: jointData.nativeParams.maxForce,
  76469. collideConnected: !!jointData.collision
  76470. };
  76471. switch (impostorJoint.joint.type) {
  76472. case BABYLON.PhysicsJoint.HingeJoint:
  76473. case BABYLON.PhysicsJoint.Hinge2Joint:
  76474. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  76475. break;
  76476. case BABYLON.PhysicsJoint.DistanceJoint:
  76477. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  76478. break;
  76479. case BABYLON.PhysicsJoint.SpringJoint:
  76480. var springData = jointData;
  76481. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  76482. restLength: springData.length,
  76483. stiffness: springData.stiffness,
  76484. damping: springData.damping,
  76485. localAnchorA: constraintData.pivotA,
  76486. localAnchorB: constraintData.pivotB
  76487. });
  76488. break;
  76489. case BABYLON.PhysicsJoint.LockJoint:
  76490. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  76491. break;
  76492. case BABYLON.PhysicsJoint.PointToPointJoint:
  76493. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  76494. default:
  76495. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  76496. break;
  76497. }
  76498. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  76499. constraint.collideConnected = !!jointData.collision;
  76500. impostorJoint.joint.physicsJoint = constraint;
  76501. //don't add spring as constraint, as it is not one.
  76502. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  76503. this.world.addConstraint(constraint);
  76504. }
  76505. else {
  76506. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  76507. constraint.applyForce();
  76508. });
  76509. }
  76510. };
  76511. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  76512. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  76513. };
  76514. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  76515. var index;
  76516. var mat;
  76517. for (index = 0; index < this._physicsMaterials.length; index++) {
  76518. mat = this._physicsMaterials[index];
  76519. if (mat.friction === friction && mat.restitution === restitution) {
  76520. return mat;
  76521. }
  76522. }
  76523. var currentMat = new this.BJSCANNON.Material(name);
  76524. currentMat.friction = friction;
  76525. currentMat.restitution = restitution;
  76526. this._physicsMaterials.push(currentMat);
  76527. return currentMat;
  76528. };
  76529. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  76530. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  76531. };
  76532. CannonJSPlugin.prototype._createShape = function (impostor) {
  76533. var object = impostor.object;
  76534. var returnValue;
  76535. var extendSize = impostor.getObjectExtendSize();
  76536. switch (impostor.type) {
  76537. case BABYLON.PhysicsImpostor.SphereImpostor:
  76538. var radiusX = extendSize.x;
  76539. var radiusY = extendSize.y;
  76540. var radiusZ = extendSize.z;
  76541. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  76542. break;
  76543. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  76544. case BABYLON.PhysicsImpostor.CylinderImpostor:
  76545. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  76546. break;
  76547. case BABYLON.PhysicsImpostor.BoxImpostor:
  76548. var box = extendSize.scale(0.5);
  76549. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  76550. break;
  76551. case BABYLON.PhysicsImpostor.PlaneImpostor:
  76552. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  76553. returnValue = new this.BJSCANNON.Plane();
  76554. break;
  76555. case BABYLON.PhysicsImpostor.MeshImpostor:
  76556. // should transform the vertex data to world coordinates!!
  76557. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  76558. var rawFaces = object.getIndices ? object.getIndices() : [];
  76559. if (!rawVerts)
  76560. return;
  76561. // get only scale! so the object could transform correctly.
  76562. var oldPosition = object.position.clone();
  76563. var oldRotation = object.rotation && object.rotation.clone();
  76564. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  76565. object.position.copyFromFloats(0, 0, 0);
  76566. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  76567. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  76568. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  76569. var transform = object.computeWorldMatrix(true);
  76570. // convert rawVerts to object space
  76571. var temp = new Array();
  76572. var index;
  76573. for (index = 0; index < rawVerts.length; index += 3) {
  76574. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  76575. }
  76576. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  76577. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  76578. //now set back the transformation!
  76579. object.position.copyFrom(oldPosition);
  76580. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  76581. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  76582. break;
  76583. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  76584. var oldPosition2 = object.position.clone();
  76585. var oldRotation2 = object.rotation && object.rotation.clone();
  76586. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  76587. object.position.copyFromFloats(0, 0, 0);
  76588. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  76589. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  76590. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  76591. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  76592. returnValue = this._createHeightmap(object);
  76593. object.position.copyFrom(oldPosition2);
  76594. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  76595. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  76596. object.computeWorldMatrix(true);
  76597. break;
  76598. case BABYLON.PhysicsImpostor.ParticleImpostor:
  76599. returnValue = new this.BJSCANNON.Particle();
  76600. break;
  76601. }
  76602. return returnValue;
  76603. };
  76604. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  76605. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  76606. var transform = object.computeWorldMatrix(true);
  76607. // convert rawVerts to object space
  76608. var temp = new Array();
  76609. var index;
  76610. for (index = 0; index < pos.length; index += 3) {
  76611. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  76612. }
  76613. pos = temp;
  76614. var matrix = new Array();
  76615. //For now pointDepth will not be used and will be automatically calculated.
  76616. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  76617. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  76618. var boundingInfo = object.getBoundingInfo();
  76619. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  76620. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  76621. var elementSize = dim * 2 / arraySize;
  76622. for (var i = 0; i < pos.length; i = i + 3) {
  76623. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  76624. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  76625. var y = -pos[i + 2] + minY;
  76626. if (!matrix[x]) {
  76627. matrix[x] = [];
  76628. }
  76629. if (!matrix[x][z]) {
  76630. matrix[x][z] = y;
  76631. }
  76632. matrix[x][z] = Math.max(y, matrix[x][z]);
  76633. }
  76634. for (var x = 0; x <= arraySize; ++x) {
  76635. if (!matrix[x]) {
  76636. var loc = 1;
  76637. while (!matrix[(x + loc) % arraySize]) {
  76638. loc++;
  76639. }
  76640. matrix[x] = matrix[(x + loc) % arraySize].slice();
  76641. //console.log("missing x", x);
  76642. }
  76643. for (var z = 0; z <= arraySize; ++z) {
  76644. if (!matrix[x][z]) {
  76645. var loc = 1;
  76646. var newValue;
  76647. while (newValue === undefined) {
  76648. newValue = matrix[x][(z + loc++) % arraySize];
  76649. }
  76650. matrix[x][z] = newValue;
  76651. }
  76652. }
  76653. }
  76654. var shape = new this.BJSCANNON.Heightfield(matrix, {
  76655. elementSize: elementSize
  76656. });
  76657. //For future reference, needed for body transformation
  76658. shape.minY = minY;
  76659. return shape;
  76660. };
  76661. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  76662. var object = impostor.object;
  76663. //make sure it is updated...
  76664. object.computeWorldMatrix && object.computeWorldMatrix(true);
  76665. // The delta between the mesh position and the mesh bounding box center
  76666. var bInfo = object.getBoundingInfo();
  76667. if (!bInfo)
  76668. return;
  76669. var center = impostor.getObjectCenter();
  76670. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  76671. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  76672. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  76673. this._tmpPosition.copyFrom(center);
  76674. var quaternion = object.rotationQuaternion;
  76675. if (!quaternion) {
  76676. return;
  76677. }
  76678. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  76679. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  76680. //-90 DEG in X, precalculated
  76681. quaternion = quaternion.multiply(this._minus90X);
  76682. //Invert! (Precalculated, 90 deg in X)
  76683. //No need to clone. this will never change.
  76684. impostor.setDeltaRotation(this._plus90X);
  76685. }
  76686. //If it is a heightfield, if should be centered.
  76687. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  76688. var mesh = object;
  76689. var boundingInfo = mesh.getBoundingInfo();
  76690. //calculate the correct body position:
  76691. var rotationQuaternion = mesh.rotationQuaternion;
  76692. mesh.rotationQuaternion = this._tmpUnityRotation;
  76693. mesh.computeWorldMatrix(true);
  76694. //get original center with no rotation
  76695. var c = center.clone();
  76696. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  76697. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  76698. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  76699. mesh.setPreTransformMatrix(p);
  76700. mesh.computeWorldMatrix(true);
  76701. //calculate the translation
  76702. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  76703. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  76704. //add it inverted to the delta
  76705. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  76706. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  76707. //rotation is back
  76708. mesh.rotationQuaternion = rotationQuaternion;
  76709. mesh.setPreTransformMatrix(oldPivot);
  76710. mesh.computeWorldMatrix(true);
  76711. }
  76712. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  76713. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  76714. //this._tmpPosition.copyFrom(object.position);
  76715. }
  76716. impostor.setDeltaPosition(this._tmpDeltaPosition);
  76717. //Now update the impostor object
  76718. impostor.physicsBody.position.copy(this._tmpPosition);
  76719. impostor.physicsBody.quaternion.copy(quaternion);
  76720. };
  76721. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  76722. impostor.object.position.copyFrom(impostor.physicsBody.position);
  76723. if (impostor.object.rotationQuaternion) {
  76724. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  76725. }
  76726. };
  76727. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  76728. impostor.physicsBody.position.copy(newPosition);
  76729. impostor.physicsBody.quaternion.copy(newRotation);
  76730. };
  76731. CannonJSPlugin.prototype.isSupported = function () {
  76732. return this.BJSCANNON !== undefined;
  76733. };
  76734. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  76735. impostor.physicsBody.velocity.copy(velocity);
  76736. };
  76737. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  76738. impostor.physicsBody.angularVelocity.copy(velocity);
  76739. };
  76740. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  76741. var v = impostor.physicsBody.velocity;
  76742. if (!v) {
  76743. return null;
  76744. }
  76745. return new BABYLON.Vector3(v.x, v.y, v.z);
  76746. };
  76747. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  76748. var v = impostor.physicsBody.angularVelocity;
  76749. if (!v) {
  76750. return null;
  76751. }
  76752. return new BABYLON.Vector3(v.x, v.y, v.z);
  76753. };
  76754. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  76755. impostor.physicsBody.mass = mass;
  76756. impostor.physicsBody.updateMassProperties();
  76757. };
  76758. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  76759. return impostor.physicsBody.mass;
  76760. };
  76761. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  76762. return impostor.physicsBody.material.friction;
  76763. };
  76764. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  76765. impostor.physicsBody.material.friction = friction;
  76766. };
  76767. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  76768. return impostor.physicsBody.material.restitution;
  76769. };
  76770. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  76771. impostor.physicsBody.material.restitution = restitution;
  76772. };
  76773. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  76774. impostor.physicsBody.sleep();
  76775. };
  76776. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  76777. impostor.physicsBody.wakeUp();
  76778. };
  76779. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  76780. joint.physicsJoint.distance = maxDistance;
  76781. };
  76782. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  76783. // if (!motorIndex) {
  76784. // joint.physicsJoint.enableMotor();
  76785. // }
  76786. // }
  76787. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  76788. // if (!motorIndex) {
  76789. // joint.physicsJoint.disableMotor();
  76790. // }
  76791. // }
  76792. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  76793. if (!motorIndex) {
  76794. joint.physicsJoint.enableMotor();
  76795. joint.physicsJoint.setMotorSpeed(speed);
  76796. if (maxForce) {
  76797. this.setLimit(joint, maxForce);
  76798. }
  76799. }
  76800. };
  76801. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  76802. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  76803. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  76804. };
  76805. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  76806. var body = impostor.physicsBody;
  76807. mesh.position.x = body.position.x;
  76808. mesh.position.y = body.position.y;
  76809. mesh.position.z = body.position.z;
  76810. if (mesh.rotationQuaternion) {
  76811. mesh.rotationQuaternion.x = body.quaternion.x;
  76812. mesh.rotationQuaternion.y = body.quaternion.y;
  76813. mesh.rotationQuaternion.z = body.quaternion.z;
  76814. mesh.rotationQuaternion.w = body.quaternion.w;
  76815. }
  76816. };
  76817. CannonJSPlugin.prototype.getRadius = function (impostor) {
  76818. var shape = impostor.physicsBody.shapes[0];
  76819. return shape.boundingSphereRadius;
  76820. };
  76821. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  76822. var shape = impostor.physicsBody.shapes[0];
  76823. result.x = shape.halfExtents.x * 2;
  76824. result.y = shape.halfExtents.y * 2;
  76825. result.z = shape.halfExtents.z * 2;
  76826. };
  76827. CannonJSPlugin.prototype.dispose = function () {
  76828. };
  76829. CannonJSPlugin.prototype._extendNamespace = function () {
  76830. //this will force cannon to execute at least one step when using interpolation
  76831. var step_tmp1 = new this.BJSCANNON.Vec3();
  76832. var Engine = this.BJSCANNON;
  76833. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  76834. maxSubSteps = maxSubSteps || 10;
  76835. timeSinceLastCalled = timeSinceLastCalled || 0;
  76836. if (timeSinceLastCalled === 0) {
  76837. this.internalStep(dt);
  76838. this.time += dt;
  76839. }
  76840. else {
  76841. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  76842. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  76843. var t0 = performance.now();
  76844. for (var i = 0; i !== internalSteps; i++) {
  76845. this.internalStep(dt);
  76846. if (performance.now() - t0 > dt * 1000) {
  76847. break;
  76848. }
  76849. }
  76850. this.time += timeSinceLastCalled;
  76851. var h = this.time % dt;
  76852. var h_div_dt = h / dt;
  76853. var interpvelo = step_tmp1;
  76854. var bodies = this.bodies;
  76855. for (var j = 0; j !== bodies.length; j++) {
  76856. var b = bodies[j];
  76857. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  76858. b.position.vsub(b.previousPosition, interpvelo);
  76859. interpvelo.scale(h_div_dt, interpvelo);
  76860. b.position.vadd(interpvelo, b.interpolatedPosition);
  76861. }
  76862. else {
  76863. b.interpolatedPosition.copy(b.position);
  76864. b.interpolatedQuaternion.copy(b.quaternion);
  76865. }
  76866. }
  76867. }
  76868. };
  76869. };
  76870. return CannonJSPlugin;
  76871. }());
  76872. BABYLON.CannonJSPlugin = CannonJSPlugin;
  76873. })(BABYLON || (BABYLON = {}));
  76874. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  76875. var BABYLON;
  76876. (function (BABYLON) {
  76877. var OimoJSPlugin = /** @class */ (function () {
  76878. function OimoJSPlugin(iterations) {
  76879. this.name = "OimoJSPlugin";
  76880. this._tmpImpostorsArray = [];
  76881. this._tmpPositionVector = BABYLON.Vector3.Zero();
  76882. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  76883. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  76884. this.world.worldscale(1);
  76885. this.world.clear();
  76886. //making sure no stats are calculated
  76887. this.world.isNoStat = true;
  76888. }
  76889. OimoJSPlugin.prototype.setGravity = function (gravity) {
  76890. this.world.gravity.copy(gravity);
  76891. };
  76892. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  76893. this.world.timeStep = timeStep;
  76894. };
  76895. OimoJSPlugin.prototype.getTimeStep = function () {
  76896. return this.world.timeStep;
  76897. };
  76898. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  76899. var _this = this;
  76900. impostors.forEach(function (impostor) {
  76901. impostor.beforeStep();
  76902. });
  76903. this.world.step();
  76904. impostors.forEach(function (impostor) {
  76905. impostor.afterStep();
  76906. //update the ordered impostors array
  76907. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  76908. });
  76909. //check for collisions
  76910. var contact = this.world.contacts;
  76911. while (contact !== null) {
  76912. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  76913. contact = contact.next;
  76914. continue;
  76915. }
  76916. //is this body colliding with any other? get the impostor
  76917. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  76918. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  76919. if (!mainImpostor || !collidingImpostor) {
  76920. contact = contact.next;
  76921. continue;
  76922. }
  76923. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  76924. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  76925. contact = contact.next;
  76926. }
  76927. };
  76928. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  76929. var mass = impostor.physicsBody.massInfo.mass;
  76930. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  76931. };
  76932. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  76933. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  76934. this.applyImpulse(impostor, force, contactPoint);
  76935. };
  76936. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  76937. var _this = this;
  76938. //parent-child relationship. Does this impostor has a parent impostor?
  76939. if (impostor.parent) {
  76940. if (impostor.physicsBody) {
  76941. this.removePhysicsBody(impostor);
  76942. //TODO is that needed?
  76943. impostor.forceUpdate();
  76944. }
  76945. return;
  76946. }
  76947. if (impostor.isBodyInitRequired()) {
  76948. var bodyConfig = {
  76949. name: impostor.uniqueId,
  76950. //Oimo must have mass, also for static objects.
  76951. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  76952. size: [],
  76953. type: [],
  76954. pos: [],
  76955. rot: [],
  76956. move: impostor.getParam("mass") !== 0,
  76957. //Supporting older versions of Oimo
  76958. world: this.world
  76959. };
  76960. var impostors = [impostor];
  76961. var addToArray = function (parent) {
  76962. if (!parent.getChildMeshes)
  76963. return;
  76964. parent.getChildMeshes().forEach(function (m) {
  76965. if (m.physicsImpostor) {
  76966. impostors.push(m.physicsImpostor);
  76967. //m.physicsImpostor._init();
  76968. }
  76969. });
  76970. };
  76971. addToArray(impostor.object);
  76972. var checkWithEpsilon_1 = function (value) {
  76973. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  76974. };
  76975. impostors.forEach(function (i) {
  76976. if (!impostor.object.rotationQuaternion) {
  76977. return;
  76978. }
  76979. //get the correct bounding box
  76980. var oldQuaternion = i.object.rotationQuaternion;
  76981. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  76982. x: impostor.object.rotationQuaternion.x,
  76983. y: impostor.object.rotationQuaternion.y,
  76984. z: impostor.object.rotationQuaternion.z,
  76985. s: impostor.object.rotationQuaternion.w
  76986. });
  76987. var extendSize = i.getObjectExtendSize();
  76988. if (i === impostor) {
  76989. var center = impostor.getObjectCenter();
  76990. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  76991. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  76992. //Can also use Array.prototype.push.apply
  76993. bodyConfig.pos.push(center.x);
  76994. bodyConfig.pos.push(center.y);
  76995. bodyConfig.pos.push(center.z);
  76996. //tmp solution
  76997. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  76998. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  76999. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  77000. }
  77001. else {
  77002. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  77003. bodyConfig.pos.push(localPosition.x);
  77004. bodyConfig.pos.push(localPosition.y);
  77005. bodyConfig.pos.push(localPosition.z);
  77006. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  77007. bodyConfig.rot.push(0);
  77008. bodyConfig.rot.push(0);
  77009. bodyConfig.rot.push(0);
  77010. }
  77011. // register mesh
  77012. switch (i.type) {
  77013. case BABYLON.PhysicsImpostor.ParticleImpostor:
  77014. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  77015. case BABYLON.PhysicsImpostor.SphereImpostor:
  77016. var radiusX = extendSize.x;
  77017. var radiusY = extendSize.y;
  77018. var radiusZ = extendSize.z;
  77019. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  77020. bodyConfig.type.push('sphere');
  77021. //due to the way oimo works with compounds, add 3 times
  77022. bodyConfig.size.push(size);
  77023. bodyConfig.size.push(size);
  77024. bodyConfig.size.push(size);
  77025. break;
  77026. case BABYLON.PhysicsImpostor.CylinderImpostor:
  77027. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  77028. var sizeY = checkWithEpsilon_1(extendSize.y);
  77029. bodyConfig.type.push('cylinder');
  77030. bodyConfig.size.push(sizeX);
  77031. bodyConfig.size.push(sizeY);
  77032. //due to the way oimo works with compounds, add one more value.
  77033. bodyConfig.size.push(sizeY);
  77034. break;
  77035. case BABYLON.PhysicsImpostor.PlaneImpostor:
  77036. case BABYLON.PhysicsImpostor.BoxImpostor:
  77037. default:
  77038. var sizeX = checkWithEpsilon_1(extendSize.x);
  77039. var sizeY = checkWithEpsilon_1(extendSize.y);
  77040. var sizeZ = checkWithEpsilon_1(extendSize.z);
  77041. bodyConfig.type.push('box');
  77042. bodyConfig.size.push(sizeX);
  77043. bodyConfig.size.push(sizeY);
  77044. bodyConfig.size.push(sizeZ);
  77045. break;
  77046. }
  77047. //actually not needed, but hey...
  77048. i.object.rotationQuaternion = oldQuaternion;
  77049. });
  77050. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  77051. }
  77052. else {
  77053. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  77054. }
  77055. impostor.setDeltaPosition(this._tmpPositionVector);
  77056. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  77057. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  77058. };
  77059. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  77060. //impostor.physicsBody.dispose();
  77061. //Same as : (older oimo versions)
  77062. this.world.removeRigidBody(impostor.physicsBody);
  77063. };
  77064. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  77065. var mainBody = impostorJoint.mainImpostor.physicsBody;
  77066. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  77067. if (!mainBody || !connectedBody) {
  77068. return;
  77069. }
  77070. var jointData = impostorJoint.joint.jointData;
  77071. var options = jointData.nativeParams || {};
  77072. var type;
  77073. var nativeJointData = {
  77074. body1: mainBody,
  77075. body2: connectedBody,
  77076. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  77077. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  77078. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  77079. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  77080. min: options.min,
  77081. max: options.max,
  77082. collision: options.collision || jointData.collision,
  77083. spring: options.spring,
  77084. //supporting older version of Oimo
  77085. world: this.world
  77086. };
  77087. switch (impostorJoint.joint.type) {
  77088. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  77089. type = "jointBall";
  77090. break;
  77091. case BABYLON.PhysicsJoint.SpringJoint:
  77092. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  77093. var springData = jointData;
  77094. nativeJointData.min = springData.length || nativeJointData.min;
  77095. //Max should also be set, just make sure it is at least min
  77096. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  77097. case BABYLON.PhysicsJoint.DistanceJoint:
  77098. type = "jointDistance";
  77099. nativeJointData.max = jointData.maxDistance;
  77100. break;
  77101. case BABYLON.PhysicsJoint.PrismaticJoint:
  77102. type = "jointPrisme";
  77103. break;
  77104. case BABYLON.PhysicsJoint.SliderJoint:
  77105. type = "jointSlide";
  77106. break;
  77107. case BABYLON.PhysicsJoint.WheelJoint:
  77108. type = "jointWheel";
  77109. break;
  77110. case BABYLON.PhysicsJoint.HingeJoint:
  77111. default:
  77112. type = "jointHinge";
  77113. break;
  77114. }
  77115. nativeJointData.type = type;
  77116. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  77117. };
  77118. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  77119. //Bug in Oimo prevents us from disposing a joint in the playground
  77120. //joint.joint.physicsJoint.dispose();
  77121. //So we will bruteforce it!
  77122. try {
  77123. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  77124. }
  77125. catch (e) {
  77126. BABYLON.Tools.Warn(e);
  77127. }
  77128. };
  77129. OimoJSPlugin.prototype.isSupported = function () {
  77130. return this.BJSOIMO !== undefined;
  77131. };
  77132. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  77133. if (!impostor.physicsBody.sleeping) {
  77134. //TODO check that
  77135. if (impostor.physicsBody.shapes.next) {
  77136. var parentShape = this._getLastShape(impostor.physicsBody);
  77137. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  77138. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  77139. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  77140. }
  77141. else {
  77142. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  77143. }
  77144. if (impostor.object.rotationQuaternion) {
  77145. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  77146. impostor.object.rotationQuaternion.normalize();
  77147. }
  77148. }
  77149. };
  77150. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  77151. var body = impostor.physicsBody;
  77152. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  77153. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  77154. body.syncShapes();
  77155. body.awake();
  77156. };
  77157. OimoJSPlugin.prototype._getLastShape = function (body) {
  77158. var lastShape = body.shapes;
  77159. while (lastShape.next) {
  77160. lastShape = lastShape.next;
  77161. }
  77162. return lastShape;
  77163. };
  77164. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  77165. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  77166. };
  77167. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  77168. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  77169. };
  77170. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  77171. var v = impostor.physicsBody.linearVelocity;
  77172. if (!v) {
  77173. return null;
  77174. }
  77175. return new BABYLON.Vector3(v.x, v.y, v.z);
  77176. };
  77177. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  77178. var v = impostor.physicsBody.angularVelocity;
  77179. if (!v) {
  77180. return null;
  77181. }
  77182. return new BABYLON.Vector3(v.x, v.y, v.z);
  77183. };
  77184. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  77185. var staticBody = mass === 0;
  77186. //this will actually set the body's density and not its mass.
  77187. //But this is how oimo treats the mass variable.
  77188. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  77189. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  77190. };
  77191. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  77192. return impostor.physicsBody.shapes.density;
  77193. };
  77194. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  77195. return impostor.physicsBody.shapes.friction;
  77196. };
  77197. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  77198. impostor.physicsBody.shapes.friction = friction;
  77199. };
  77200. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  77201. return impostor.physicsBody.shapes.restitution;
  77202. };
  77203. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  77204. impostor.physicsBody.shapes.restitution = restitution;
  77205. };
  77206. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  77207. impostor.physicsBody.sleep();
  77208. };
  77209. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  77210. impostor.physicsBody.awake();
  77211. };
  77212. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  77213. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  77214. if (minDistance !== void 0) {
  77215. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  77216. }
  77217. };
  77218. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  77219. //TODO separate rotational and transational motors.
  77220. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  77221. if (motor) {
  77222. motor.setMotor(speed, maxForce);
  77223. }
  77224. };
  77225. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  77226. //TODO separate rotational and transational motors.
  77227. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  77228. if (motor) {
  77229. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  77230. }
  77231. };
  77232. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  77233. var body = impostor.physicsBody;
  77234. mesh.position.x = body.position.x;
  77235. mesh.position.y = body.position.y;
  77236. mesh.position.z = body.position.z;
  77237. if (mesh.rotationQuaternion) {
  77238. mesh.rotationQuaternion.x = body.orientation.x;
  77239. mesh.rotationQuaternion.y = body.orientation.y;
  77240. mesh.rotationQuaternion.z = body.orientation.z;
  77241. mesh.rotationQuaternion.w = body.orientation.s;
  77242. }
  77243. };
  77244. OimoJSPlugin.prototype.getRadius = function (impostor) {
  77245. return impostor.physicsBody.shapes.radius;
  77246. };
  77247. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  77248. var shape = impostor.physicsBody.shapes;
  77249. result.x = shape.halfWidth * 2;
  77250. result.y = shape.halfHeight * 2;
  77251. result.z = shape.halfDepth * 2;
  77252. };
  77253. OimoJSPlugin.prototype.dispose = function () {
  77254. this.world.clear();
  77255. };
  77256. return OimoJSPlugin;
  77257. }());
  77258. BABYLON.OimoJSPlugin = OimoJSPlugin;
  77259. })(BABYLON || (BABYLON = {}));
  77260. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  77261. var BABYLON;
  77262. (function (BABYLON) {
  77263. /*
  77264. * Based on jsTGALoader - Javascript loader for TGA file
  77265. * By Vincent Thibault
  77266. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  77267. */
  77268. var TGATools = /** @class */ (function () {
  77269. function TGATools() {
  77270. }
  77271. TGATools.GetTGAHeader = function (data) {
  77272. var offset = 0;
  77273. var header = {
  77274. id_length: data[offset++],
  77275. colormap_type: data[offset++],
  77276. image_type: data[offset++],
  77277. colormap_index: data[offset++] | data[offset++] << 8,
  77278. colormap_length: data[offset++] | data[offset++] << 8,
  77279. colormap_size: data[offset++],
  77280. origin: [
  77281. data[offset++] | data[offset++] << 8,
  77282. data[offset++] | data[offset++] << 8
  77283. ],
  77284. width: data[offset++] | data[offset++] << 8,
  77285. height: data[offset++] | data[offset++] << 8,
  77286. pixel_size: data[offset++],
  77287. flags: data[offset++]
  77288. };
  77289. return header;
  77290. };
  77291. TGATools.UploadContent = function (gl, data) {
  77292. // Not enough data to contain header ?
  77293. if (data.length < 19) {
  77294. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  77295. return;
  77296. }
  77297. // Read Header
  77298. var offset = 18;
  77299. var header = TGATools.GetTGAHeader(data);
  77300. // Assume it's a valid Targa file.
  77301. if (header.id_length + offset > data.length) {
  77302. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  77303. return;
  77304. }
  77305. // Skip not needed data
  77306. offset += header.id_length;
  77307. var use_rle = false;
  77308. var use_pal = false;
  77309. var use_grey = false;
  77310. // Get some informations.
  77311. switch (header.image_type) {
  77312. case TGATools._TYPE_RLE_INDEXED:
  77313. use_rle = true;
  77314. case TGATools._TYPE_INDEXED:
  77315. use_pal = true;
  77316. break;
  77317. case TGATools._TYPE_RLE_RGB:
  77318. use_rle = true;
  77319. case TGATools._TYPE_RGB:
  77320. // use_rgb = true;
  77321. break;
  77322. case TGATools._TYPE_RLE_GREY:
  77323. use_rle = true;
  77324. case TGATools._TYPE_GREY:
  77325. use_grey = true;
  77326. break;
  77327. }
  77328. var pixel_data;
  77329. // var numAlphaBits = header.flags & 0xf;
  77330. var pixel_size = header.pixel_size >> 3;
  77331. var pixel_total = header.width * header.height * pixel_size;
  77332. // Read palettes
  77333. var palettes;
  77334. if (use_pal) {
  77335. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  77336. }
  77337. // Read LRE
  77338. if (use_rle) {
  77339. pixel_data = new Uint8Array(pixel_total);
  77340. var c, count, i;
  77341. var localOffset = 0;
  77342. var pixels = new Uint8Array(pixel_size);
  77343. while (offset < pixel_total && localOffset < pixel_total) {
  77344. c = data[offset++];
  77345. count = (c & 0x7f) + 1;
  77346. // RLE pixels
  77347. if (c & 0x80) {
  77348. // Bind pixel tmp array
  77349. for (i = 0; i < pixel_size; ++i) {
  77350. pixels[i] = data[offset++];
  77351. }
  77352. // Copy pixel array
  77353. for (i = 0; i < count; ++i) {
  77354. pixel_data.set(pixels, localOffset + i * pixel_size);
  77355. }
  77356. localOffset += pixel_size * count;
  77357. }
  77358. else {
  77359. count *= pixel_size;
  77360. for (i = 0; i < count; ++i) {
  77361. pixel_data[localOffset + i] = data[offset++];
  77362. }
  77363. localOffset += count;
  77364. }
  77365. }
  77366. }
  77367. else {
  77368. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  77369. }
  77370. // Load to texture
  77371. var x_start, y_start, x_step, y_step, y_end, x_end;
  77372. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  77373. default:
  77374. case TGATools._ORIGIN_UL:
  77375. x_start = 0;
  77376. x_step = 1;
  77377. x_end = header.width;
  77378. y_start = 0;
  77379. y_step = 1;
  77380. y_end = header.height;
  77381. break;
  77382. case TGATools._ORIGIN_BL:
  77383. x_start = 0;
  77384. x_step = 1;
  77385. x_end = header.width;
  77386. y_start = header.height - 1;
  77387. y_step = -1;
  77388. y_end = -1;
  77389. break;
  77390. case TGATools._ORIGIN_UR:
  77391. x_start = header.width - 1;
  77392. x_step = -1;
  77393. x_end = -1;
  77394. y_start = 0;
  77395. y_step = 1;
  77396. y_end = header.height;
  77397. break;
  77398. case TGATools._ORIGIN_BR:
  77399. x_start = header.width - 1;
  77400. x_step = -1;
  77401. x_end = -1;
  77402. y_start = header.height - 1;
  77403. y_step = -1;
  77404. y_end = -1;
  77405. break;
  77406. }
  77407. // Load the specify method
  77408. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  77409. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  77410. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  77411. };
  77412. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77413. var image = pixel_data, colormap = palettes;
  77414. var width = header.width, height = header.height;
  77415. var color, i = 0, x, y;
  77416. var imageData = new Uint8Array(width * height * 4);
  77417. for (y = y_start; y !== y_end; y += y_step) {
  77418. for (x = x_start; x !== x_end; x += x_step, i++) {
  77419. color = image[i];
  77420. imageData[(x + width * y) * 4 + 3] = 255;
  77421. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  77422. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  77423. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  77424. }
  77425. }
  77426. return imageData;
  77427. };
  77428. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77429. var image = pixel_data;
  77430. var width = header.width, height = header.height;
  77431. var color, i = 0, x, y;
  77432. var imageData = new Uint8Array(width * height * 4);
  77433. for (y = y_start; y !== y_end; y += y_step) {
  77434. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  77435. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  77436. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  77437. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  77438. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  77439. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  77440. }
  77441. }
  77442. return imageData;
  77443. };
  77444. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77445. var image = pixel_data;
  77446. var width = header.width, height = header.height;
  77447. var i = 0, x, y;
  77448. var imageData = new Uint8Array(width * height * 4);
  77449. for (y = y_start; y !== y_end; y += y_step) {
  77450. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  77451. imageData[(x + width * y) * 4 + 3] = 255;
  77452. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  77453. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  77454. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  77455. }
  77456. }
  77457. return imageData;
  77458. };
  77459. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77460. var image = pixel_data;
  77461. var width = header.width, height = header.height;
  77462. var i = 0, x, y;
  77463. var imageData = new Uint8Array(width * height * 4);
  77464. for (y = y_start; y !== y_end; y += y_step) {
  77465. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  77466. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  77467. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  77468. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  77469. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  77470. }
  77471. }
  77472. return imageData;
  77473. };
  77474. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77475. var image = pixel_data;
  77476. var width = header.width, height = header.height;
  77477. var color, i = 0, x, y;
  77478. var imageData = new Uint8Array(width * height * 4);
  77479. for (y = y_start; y !== y_end; y += y_step) {
  77480. for (x = x_start; x !== x_end; x += x_step, i++) {
  77481. color = image[i];
  77482. imageData[(x + width * y) * 4 + 0] = color;
  77483. imageData[(x + width * y) * 4 + 1] = color;
  77484. imageData[(x + width * y) * 4 + 2] = color;
  77485. imageData[(x + width * y) * 4 + 3] = 255;
  77486. }
  77487. }
  77488. return imageData;
  77489. };
  77490. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77491. var image = pixel_data;
  77492. var width = header.width, height = header.height;
  77493. var i = 0, x, y;
  77494. var imageData = new Uint8Array(width * height * 4);
  77495. for (y = y_start; y !== y_end; y += y_step) {
  77496. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  77497. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  77498. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  77499. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  77500. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  77501. }
  77502. }
  77503. return imageData;
  77504. };
  77505. //private static _TYPE_NO_DATA = 0;
  77506. TGATools._TYPE_INDEXED = 1;
  77507. TGATools._TYPE_RGB = 2;
  77508. TGATools._TYPE_GREY = 3;
  77509. TGATools._TYPE_RLE_INDEXED = 9;
  77510. TGATools._TYPE_RLE_RGB = 10;
  77511. TGATools._TYPE_RLE_GREY = 11;
  77512. TGATools._ORIGIN_MASK = 0x30;
  77513. TGATools._ORIGIN_SHIFT = 0x04;
  77514. TGATools._ORIGIN_BL = 0x00;
  77515. TGATools._ORIGIN_BR = 0x01;
  77516. TGATools._ORIGIN_UL = 0x02;
  77517. TGATools._ORIGIN_UR = 0x03;
  77518. return TGATools;
  77519. }());
  77520. BABYLON.TGATools = TGATools;
  77521. })(BABYLON || (BABYLON = {}));
  77522. //# sourceMappingURL=babylon.tga.js.map
  77523. var BABYLON;
  77524. (function (BABYLON) {
  77525. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  77526. // All values and structures referenced from:
  77527. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  77528. var DDS_MAGIC = 0x20534444;
  77529. var
  77530. //DDSD_CAPS = 0x1,
  77531. //DDSD_HEIGHT = 0x2,
  77532. //DDSD_WIDTH = 0x4,
  77533. //DDSD_PITCH = 0x8,
  77534. //DDSD_PIXELFORMAT = 0x1000,
  77535. DDSD_MIPMAPCOUNT = 0x20000;
  77536. //DDSD_LINEARSIZE = 0x80000,
  77537. //DDSD_DEPTH = 0x800000;
  77538. // var DDSCAPS_COMPLEX = 0x8,
  77539. // DDSCAPS_MIPMAP = 0x400000,
  77540. // DDSCAPS_TEXTURE = 0x1000;
  77541. var DDSCAPS2_CUBEMAP = 0x200;
  77542. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  77543. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  77544. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  77545. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  77546. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  77547. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  77548. // DDSCAPS2_VOLUME = 0x200000;
  77549. var
  77550. //DDPF_ALPHAPIXELS = 0x1,
  77551. //DDPF_ALPHA = 0x2,
  77552. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  77553. //DDPF_YUV = 0x200,
  77554. DDPF_LUMINANCE = 0x20000;
  77555. function FourCCToInt32(value) {
  77556. return value.charCodeAt(0) +
  77557. (value.charCodeAt(1) << 8) +
  77558. (value.charCodeAt(2) << 16) +
  77559. (value.charCodeAt(3) << 24);
  77560. }
  77561. function Int32ToFourCC(value) {
  77562. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  77563. }
  77564. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  77565. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  77566. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  77567. var FOURCC_DX10 = FourCCToInt32("DX10");
  77568. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  77569. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  77570. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  77571. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  77572. var headerLengthInt = 31; // The header length in 32 bit ints
  77573. // Offsets into the header array
  77574. var off_magic = 0;
  77575. var off_size = 1;
  77576. var off_flags = 2;
  77577. var off_height = 3;
  77578. var off_width = 4;
  77579. var off_mipmapCount = 7;
  77580. var off_pfFlags = 20;
  77581. var off_pfFourCC = 21;
  77582. var off_RGBbpp = 22;
  77583. var off_RMask = 23;
  77584. var off_GMask = 24;
  77585. var off_BMask = 25;
  77586. var off_AMask = 26;
  77587. // var off_caps1 = 27;
  77588. var off_caps2 = 28;
  77589. // var off_caps3 = 29;
  77590. // var off_caps4 = 30;
  77591. var off_dxgiFormat = 32;
  77592. ;
  77593. var DDSTools = /** @class */ (function () {
  77594. function DDSTools() {
  77595. }
  77596. DDSTools.GetDDSInfo = function (arrayBuffer) {
  77597. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  77598. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  77599. var mipmapCount = 1;
  77600. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  77601. mipmapCount = Math.max(1, header[off_mipmapCount]);
  77602. }
  77603. var fourCC = header[off_pfFourCC];
  77604. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  77605. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77606. switch (fourCC) {
  77607. case FOURCC_D3DFMT_R16G16B16A16F:
  77608. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77609. break;
  77610. case FOURCC_D3DFMT_R32G32B32A32F:
  77611. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77612. break;
  77613. case FOURCC_DX10:
  77614. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  77615. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77616. break;
  77617. }
  77618. }
  77619. return {
  77620. width: header[off_width],
  77621. height: header[off_height],
  77622. mipmapCount: mipmapCount,
  77623. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  77624. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  77625. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  77626. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  77627. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  77628. dxgiFormat: dxgiFormat,
  77629. textureType: textureType
  77630. };
  77631. };
  77632. DDSTools._ToHalfFloat = function (value) {
  77633. if (!DDSTools._FloatView) {
  77634. DDSTools._FloatView = new Float32Array(1);
  77635. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  77636. }
  77637. DDSTools._FloatView[0] = value;
  77638. var x = DDSTools._Int32View[0];
  77639. var bits = (x >> 16) & 0x8000; /* Get the sign */
  77640. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  77641. var e = (x >> 23) & 0xff; /* Using int is faster here */
  77642. /* If zero, or denormal, or exponent underflows too much for a denormal
  77643. * half, return signed zero. */
  77644. if (e < 103) {
  77645. return bits;
  77646. }
  77647. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  77648. if (e > 142) {
  77649. bits |= 0x7c00;
  77650. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  77651. * not Inf, so make sure we set one mantissa bit too. */
  77652. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  77653. return bits;
  77654. }
  77655. /* If exponent underflows but not too much, return a denormal */
  77656. if (e < 113) {
  77657. m |= 0x0800;
  77658. /* Extra rounding may overflow and set mantissa to 0 and exponent
  77659. * to 1, which is OK. */
  77660. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  77661. return bits;
  77662. }
  77663. bits |= ((e - 112) << 10) | (m >> 1);
  77664. bits += m & 1;
  77665. return bits;
  77666. };
  77667. DDSTools._FromHalfFloat = function (value) {
  77668. var s = (value & 0x8000) >> 15;
  77669. var e = (value & 0x7C00) >> 10;
  77670. var f = value & 0x03FF;
  77671. if (e === 0) {
  77672. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  77673. }
  77674. else if (e == 0x1F) {
  77675. return f ? NaN : ((s ? -1 : 1) * Infinity);
  77676. }
  77677. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  77678. };
  77679. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77680. var destArray = new Float32Array(dataLength);
  77681. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77682. var index = 0;
  77683. for (var y = 0; y < height; y++) {
  77684. for (var x = 0; x < width; x++) {
  77685. var srcPos = (x + y * width) * 4;
  77686. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  77687. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  77688. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  77689. if (DDSTools.StoreLODInAlphaChannel) {
  77690. destArray[index + 3] = lod;
  77691. }
  77692. else {
  77693. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  77694. }
  77695. index += 4;
  77696. }
  77697. }
  77698. return destArray;
  77699. };
  77700. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77701. if (DDSTools.StoreLODInAlphaChannel) {
  77702. var destArray = new Uint16Array(dataLength);
  77703. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77704. var index = 0;
  77705. for (var y = 0; y < height; y++) {
  77706. for (var x = 0; x < width; x++) {
  77707. var srcPos = (x + y * width) * 4;
  77708. destArray[index] = srcData[srcPos];
  77709. destArray[index + 1] = srcData[srcPos + 1];
  77710. destArray[index + 2] = srcData[srcPos + 2];
  77711. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  77712. index += 4;
  77713. }
  77714. }
  77715. return destArray;
  77716. }
  77717. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  77718. };
  77719. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77720. if (DDSTools.StoreLODInAlphaChannel) {
  77721. var destArray = new Float32Array(dataLength);
  77722. var srcData = new Float32Array(arrayBuffer, dataOffset);
  77723. var index = 0;
  77724. for (var y = 0; y < height; y++) {
  77725. for (var x = 0; x < width; x++) {
  77726. var srcPos = (x + y * width) * 4;
  77727. destArray[index] = srcData[srcPos];
  77728. destArray[index + 1] = srcData[srcPos + 1];
  77729. destArray[index + 2] = srcData[srcPos + 2];
  77730. destArray[index + 3] = lod;
  77731. index += 4;
  77732. }
  77733. }
  77734. return destArray;
  77735. }
  77736. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  77737. };
  77738. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77739. var destArray = new Uint8Array(dataLength);
  77740. var srcData = new Float32Array(arrayBuffer, dataOffset);
  77741. var index = 0;
  77742. for (var y = 0; y < height; y++) {
  77743. for (var x = 0; x < width; x++) {
  77744. var srcPos = (x + y * width) * 4;
  77745. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  77746. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  77747. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  77748. if (DDSTools.StoreLODInAlphaChannel) {
  77749. destArray[index + 3] = lod;
  77750. }
  77751. else {
  77752. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  77753. }
  77754. index += 4;
  77755. }
  77756. }
  77757. return destArray;
  77758. };
  77759. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77760. var destArray = new Uint8Array(dataLength);
  77761. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77762. var index = 0;
  77763. for (var y = 0; y < height; y++) {
  77764. for (var x = 0; x < width; x++) {
  77765. var srcPos = (x + y * width) * 4;
  77766. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  77767. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  77768. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  77769. if (DDSTools.StoreLODInAlphaChannel) {
  77770. destArray[index + 3] = lod;
  77771. }
  77772. else {
  77773. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  77774. }
  77775. index += 4;
  77776. }
  77777. }
  77778. return destArray;
  77779. };
  77780. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  77781. var byteArray = new Uint8Array(dataLength);
  77782. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  77783. var index = 0;
  77784. for (var y = 0; y < height; y++) {
  77785. for (var x = 0; x < width; x++) {
  77786. var srcPos = (x + y * width) * 4;
  77787. byteArray[index] = srcData[srcPos + rOffset];
  77788. byteArray[index + 1] = srcData[srcPos + gOffset];
  77789. byteArray[index + 2] = srcData[srcPos + bOffset];
  77790. byteArray[index + 3] = srcData[srcPos + aOffset];
  77791. index += 4;
  77792. }
  77793. }
  77794. return byteArray;
  77795. };
  77796. DDSTools._ExtractLongWordOrder = function (value) {
  77797. if (value === 0 || value === 255 || value === -16777216) {
  77798. return 0;
  77799. }
  77800. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  77801. };
  77802. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  77803. var byteArray = new Uint8Array(dataLength);
  77804. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  77805. var index = 0;
  77806. for (var y = 0; y < height; y++) {
  77807. for (var x = 0; x < width; x++) {
  77808. var srcPos = (x + y * width) * 3;
  77809. byteArray[index] = srcData[srcPos + rOffset];
  77810. byteArray[index + 1] = srcData[srcPos + gOffset];
  77811. byteArray[index + 2] = srcData[srcPos + bOffset];
  77812. index += 3;
  77813. }
  77814. }
  77815. return byteArray;
  77816. };
  77817. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  77818. var byteArray = new Uint8Array(dataLength);
  77819. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  77820. var index = 0;
  77821. for (var y = 0; y < height; y++) {
  77822. for (var x = 0; x < width; x++) {
  77823. var srcPos = (x + y * width);
  77824. byteArray[index] = srcData[srcPos];
  77825. index++;
  77826. }
  77827. }
  77828. return byteArray;
  77829. };
  77830. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  77831. if (lodIndex === void 0) { lodIndex = -1; }
  77832. var ext = engine.getCaps().s3tc;
  77833. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  77834. var fourCC, width, height, dataLength = 0, dataOffset;
  77835. var byteArray, mipmapCount, mip;
  77836. var internalFormat = 0;
  77837. var format = 0;
  77838. var blockBytes = 1;
  77839. if (header[off_magic] !== DDS_MAGIC) {
  77840. BABYLON.Tools.Error("Invalid magic number in DDS header");
  77841. return;
  77842. }
  77843. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  77844. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  77845. return;
  77846. }
  77847. if (info.isCompressed && !ext) {
  77848. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  77849. return;
  77850. }
  77851. var bpp = header[off_RGBbpp];
  77852. dataOffset = header[off_size] + 4;
  77853. var computeFormats = false;
  77854. if (info.isFourCC) {
  77855. fourCC = header[off_pfFourCC];
  77856. switch (fourCC) {
  77857. case FOURCC_DXT1:
  77858. blockBytes = 8;
  77859. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  77860. break;
  77861. case FOURCC_DXT3:
  77862. blockBytes = 16;
  77863. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  77864. break;
  77865. case FOURCC_DXT5:
  77866. blockBytes = 16;
  77867. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  77868. break;
  77869. case FOURCC_D3DFMT_R16G16B16A16F:
  77870. computeFormats = true;
  77871. break;
  77872. case FOURCC_D3DFMT_R32G32B32A32F:
  77873. computeFormats = true;
  77874. break;
  77875. case FOURCC_DX10:
  77876. // There is an additionnal header so dataOffset need to be changed
  77877. dataOffset += 5 * 4; // 5 uints
  77878. var supported = false;
  77879. switch (info.dxgiFormat) {
  77880. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  77881. computeFormats = true;
  77882. supported = true;
  77883. break;
  77884. case DXGI_FORMAT_B8G8R8X8_UNORM:
  77885. info.isRGB = true;
  77886. info.isFourCC = false;
  77887. bpp = 32;
  77888. supported = true;
  77889. break;
  77890. }
  77891. if (supported) {
  77892. break;
  77893. }
  77894. default:
  77895. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  77896. return;
  77897. }
  77898. }
  77899. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  77900. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  77901. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  77902. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  77903. if (computeFormats) {
  77904. format = engine._getWebGLTextureType(info.textureType);
  77905. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  77906. }
  77907. mipmapCount = 1;
  77908. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  77909. mipmapCount = Math.max(1, header[off_mipmapCount]);
  77910. }
  77911. for (var face = 0; face < faces; face++) {
  77912. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  77913. width = header[off_width];
  77914. height = header[off_height];
  77915. for (mip = 0; mip < mipmapCount; ++mip) {
  77916. if (lodIndex === -1 || lodIndex === mip) {
  77917. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  77918. var i = (lodIndex === -1) ? mip : 0;
  77919. if (!info.isCompressed && info.isFourCC) {
  77920. dataLength = width * height * 4;
  77921. var floatArray = null;
  77922. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  77923. if (bpp === 128) {
  77924. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77925. }
  77926. else if (bpp === 64) {
  77927. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77928. }
  77929. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77930. format = engine._getWebGLTextureType(info.textureType);
  77931. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  77932. }
  77933. else {
  77934. if (bpp === 128) {
  77935. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77936. }
  77937. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  77938. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77939. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77940. format = engine._getWebGLTextureType(info.textureType);
  77941. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  77942. }
  77943. else {
  77944. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77945. }
  77946. }
  77947. if (floatArray) {
  77948. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  77949. }
  77950. }
  77951. else if (info.isRGB) {
  77952. if (bpp === 24) {
  77953. dataLength = width * height * 3;
  77954. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  77955. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  77956. }
  77957. else {
  77958. dataLength = width * height * 4;
  77959. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  77960. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  77961. }
  77962. }
  77963. else if (info.isLuminance) {
  77964. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  77965. var unpaddedRowSize = width;
  77966. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  77967. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  77968. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  77969. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  77970. }
  77971. else {
  77972. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  77973. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  77974. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  77975. }
  77976. }
  77977. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  77978. width *= 0.5;
  77979. height *= 0.5;
  77980. width = Math.max(1.0, width);
  77981. height = Math.max(1.0, height);
  77982. }
  77983. if (currentFace !== undefined) {
  77984. // Loading a single face
  77985. break;
  77986. }
  77987. }
  77988. };
  77989. DDSTools.StoreLODInAlphaChannel = false;
  77990. return DDSTools;
  77991. }());
  77992. BABYLON.DDSTools = DDSTools;
  77993. })(BABYLON || (BABYLON = {}));
  77994. //# sourceMappingURL=babylon.dds.js.map
  77995. var BABYLON;
  77996. (function (BABYLON) {
  77997. /**
  77998. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  77999. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  78000. */
  78001. var KhronosTextureContainer = /** @class */ (function () {
  78002. /**
  78003. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  78004. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  78005. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  78006. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  78007. */
  78008. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  78009. this.arrayBuffer = arrayBuffer;
  78010. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  78011. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  78012. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  78013. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  78014. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  78015. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  78016. BABYLON.Tools.Error("texture missing KTX identifier");
  78017. return;
  78018. }
  78019. // load the reset of the header in native 32 bit int
  78020. var header = new Int32Array(this.arrayBuffer, 12, 13);
  78021. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  78022. var oppositeEndianess = header[0] === 0x01020304;
  78023. // read all the header elements in order they exist in the file, without modification (sans endainness)
  78024. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  78025. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  78026. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  78027. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  78028. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  78029. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  78030. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  78031. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  78032. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  78033. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  78034. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  78035. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  78036. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  78037. if (this.glType !== 0) {
  78038. BABYLON.Tools.Error("only compressed formats currently supported");
  78039. return;
  78040. }
  78041. else {
  78042. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  78043. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  78044. }
  78045. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  78046. BABYLON.Tools.Error("only 2D textures currently supported");
  78047. return;
  78048. }
  78049. if (this.numberOfArrayElements !== 0) {
  78050. BABYLON.Tools.Error("texture arrays not currently supported");
  78051. return;
  78052. }
  78053. if (this.numberOfFaces !== facesExpected) {
  78054. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  78055. return;
  78056. }
  78057. // we now have a completely validated file, so could use existence of loadType as success
  78058. // would need to make this more elaborate & adjust checks above to support more than one load type
  78059. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  78060. }
  78061. // not as fast hardware based, but will probably never need to use
  78062. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  78063. return ((val & 0xFF) << 24)
  78064. | ((val & 0xFF00) << 8)
  78065. | ((val >> 8) & 0xFF00)
  78066. | ((val >> 24) & 0xFF);
  78067. };
  78068. /**
  78069. * It is assumed that the texture has already been created & is currently bound
  78070. */
  78071. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  78072. switch (this.loadType) {
  78073. case KhronosTextureContainer.COMPRESSED_2D:
  78074. this._upload2DCompressedLevels(gl, loadMipmaps);
  78075. break;
  78076. case KhronosTextureContainer.TEX_2D:
  78077. case KhronosTextureContainer.COMPRESSED_3D:
  78078. case KhronosTextureContainer.TEX_3D:
  78079. }
  78080. };
  78081. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  78082. // initialize width & height for level 1
  78083. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  78084. var width = this.pixelWidth;
  78085. var height = this.pixelHeight;
  78086. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  78087. for (var level = 0; level < mipmapCount; level++) {
  78088. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  78089. for (var face = 0; face < this.numberOfFaces; face++) {
  78090. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  78091. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  78092. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  78093. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  78094. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  78095. }
  78096. width = Math.max(1.0, width * 0.5);
  78097. height = Math.max(1.0, height * 0.5);
  78098. }
  78099. };
  78100. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  78101. // load types
  78102. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  78103. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  78104. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  78105. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  78106. return KhronosTextureContainer;
  78107. }());
  78108. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  78109. })(BABYLON || (BABYLON = {}));
  78110. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  78111. var BABYLON;
  78112. (function (BABYLON) {
  78113. var Debug = /** @class */ (function () {
  78114. function Debug() {
  78115. }
  78116. Debug.AxesViewer = /** @class */ (function () {
  78117. function AxesViewer(scene, scaleLines) {
  78118. if (scaleLines === void 0) { scaleLines = 1; }
  78119. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78120. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78121. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78122. this.scaleLines = 1;
  78123. this.scaleLines = scaleLines;
  78124. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  78125. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  78126. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  78127. this._xmesh.renderingGroupId = 2;
  78128. this._ymesh.renderingGroupId = 2;
  78129. this._zmesh.renderingGroupId = 2;
  78130. this._xmesh.material.checkReadyOnlyOnce = true;
  78131. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  78132. this._ymesh.material.checkReadyOnlyOnce = true;
  78133. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  78134. this._zmesh.material.checkReadyOnlyOnce = true;
  78135. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  78136. this.scene = scene;
  78137. }
  78138. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  78139. var scaleLines = this.scaleLines;
  78140. if (this._xmesh) {
  78141. this._xmesh.position.copyFrom(position);
  78142. }
  78143. if (this._ymesh) {
  78144. this._ymesh.position.copyFrom(position);
  78145. }
  78146. if (this._zmesh) {
  78147. this._zmesh.position.copyFrom(position);
  78148. }
  78149. var point2 = this._xline[1];
  78150. point2.x = xaxis.x * scaleLines;
  78151. point2.y = xaxis.y * scaleLines;
  78152. point2.z = xaxis.z * scaleLines;
  78153. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  78154. point2 = this._yline[1];
  78155. point2.x = yaxis.x * scaleLines;
  78156. point2.y = yaxis.y * scaleLines;
  78157. point2.z = yaxis.z * scaleLines;
  78158. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  78159. point2 = this._zline[1];
  78160. point2.x = zaxis.x * scaleLines;
  78161. point2.y = zaxis.y * scaleLines;
  78162. point2.z = zaxis.z * scaleLines;
  78163. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  78164. };
  78165. AxesViewer.prototype.dispose = function () {
  78166. if (this._xmesh) {
  78167. this._xmesh.dispose();
  78168. }
  78169. if (this._ymesh) {
  78170. this._ymesh.dispose();
  78171. }
  78172. if (this._zmesh) {
  78173. this._zmesh.dispose();
  78174. }
  78175. this._xmesh = null;
  78176. this._ymesh = null;
  78177. this._zmesh = null;
  78178. this.scene = null;
  78179. };
  78180. return AxesViewer;
  78181. }());
  78182. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  78183. __extends(BoneAxesViewer, _super);
  78184. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  78185. if (scaleLines === void 0) { scaleLines = 1; }
  78186. var _this = _super.call(this, scene, scaleLines) || this;
  78187. _this.pos = BABYLON.Vector3.Zero();
  78188. _this.xaxis = BABYLON.Vector3.Zero();
  78189. _this.yaxis = BABYLON.Vector3.Zero();
  78190. _this.zaxis = BABYLON.Vector3.Zero();
  78191. _this.mesh = mesh;
  78192. _this.bone = bone;
  78193. return _this;
  78194. }
  78195. BoneAxesViewer.prototype.update = function () {
  78196. if (!this.mesh || !this.bone) {
  78197. return;
  78198. }
  78199. var bone = this.bone;
  78200. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  78201. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  78202. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  78203. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  78204. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  78205. };
  78206. BoneAxesViewer.prototype.dispose = function () {
  78207. if (this.mesh) {
  78208. this.mesh = null;
  78209. this.bone = null;
  78210. _super.prototype.dispose.call(this);
  78211. }
  78212. };
  78213. return BoneAxesViewer;
  78214. }(Debug.AxesViewer));
  78215. Debug.PhysicsViewer = /** @class */ (function () {
  78216. function PhysicsViewer(scene) {
  78217. this._impostors = [];
  78218. this._meshes = [];
  78219. this._numMeshes = 0;
  78220. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  78221. var physicEngine = this._scene.getPhysicsEngine();
  78222. if (physicEngine) {
  78223. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  78224. }
  78225. }
  78226. PhysicsViewer.prototype._updateDebugMeshes = function () {
  78227. var plugin = this._physicsEnginePlugin;
  78228. for (var i = 0; i < this._numMeshes; i++) {
  78229. var impostor = this._impostors[i];
  78230. if (!impostor) {
  78231. continue;
  78232. }
  78233. if (impostor.isDisposed) {
  78234. this.hideImpostor(this._impostors[i--]);
  78235. }
  78236. else {
  78237. var mesh = this._meshes[i];
  78238. if (mesh && plugin) {
  78239. plugin.syncMeshWithImpostor(mesh, impostor);
  78240. }
  78241. }
  78242. }
  78243. };
  78244. PhysicsViewer.prototype.showImpostor = function (impostor) {
  78245. if (!this._scene) {
  78246. return;
  78247. }
  78248. for (var i = 0; i < this._numMeshes; i++) {
  78249. if (this._impostors[i] == impostor) {
  78250. return;
  78251. }
  78252. }
  78253. var debugMesh = this._getDebugMesh(impostor, this._scene);
  78254. if (debugMesh) {
  78255. this._impostors[this._numMeshes] = impostor;
  78256. this._meshes[this._numMeshes] = debugMesh;
  78257. if (this._numMeshes === 0) {
  78258. this._renderFunction = this._updateDebugMeshes.bind(this);
  78259. this._scene.registerBeforeRender(this._renderFunction);
  78260. }
  78261. this._numMeshes++;
  78262. }
  78263. };
  78264. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  78265. if (!impostor || !this._scene) {
  78266. return;
  78267. }
  78268. var removed = false;
  78269. for (var i = 0; i < this._numMeshes; i++) {
  78270. if (this._impostors[i] == impostor) {
  78271. var mesh = this._meshes[i];
  78272. if (!mesh) {
  78273. continue;
  78274. }
  78275. this._scene.removeMesh(mesh);
  78276. mesh.dispose();
  78277. this._numMeshes--;
  78278. if (this._numMeshes > 0) {
  78279. this._meshes[i] = this._meshes[this._numMeshes];
  78280. this._impostors[i] = this._impostors[this._numMeshes];
  78281. this._meshes[this._numMeshes] = null;
  78282. this._impostors[this._numMeshes] = null;
  78283. }
  78284. else {
  78285. this._meshes[0] = null;
  78286. this._impostors[0] = null;
  78287. }
  78288. removed = true;
  78289. break;
  78290. }
  78291. }
  78292. if (removed && this._numMeshes === 0) {
  78293. this._scene.unregisterBeforeRender(this._renderFunction);
  78294. }
  78295. };
  78296. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  78297. if (!this._debugMaterial) {
  78298. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  78299. this._debugMaterial.wireframe = true;
  78300. }
  78301. return this._debugMaterial;
  78302. };
  78303. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  78304. if (!this._debugBoxMesh) {
  78305. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  78306. this._debugBoxMesh.renderingGroupId = 1;
  78307. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  78308. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  78309. scene.removeMesh(this._debugBoxMesh);
  78310. }
  78311. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  78312. };
  78313. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  78314. if (!this._debugSphereMesh) {
  78315. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  78316. this._debugSphereMesh.renderingGroupId = 1;
  78317. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  78318. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  78319. scene.removeMesh(this._debugSphereMesh);
  78320. }
  78321. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  78322. };
  78323. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  78324. var mesh = null;
  78325. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  78326. mesh = this._getDebugBoxMesh(scene);
  78327. impostor.getBoxSizeToRef(mesh.scaling);
  78328. }
  78329. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  78330. mesh = this._getDebugSphereMesh(scene);
  78331. var radius = impostor.getRadius();
  78332. mesh.scaling.x = radius * 2;
  78333. mesh.scaling.y = radius * 2;
  78334. mesh.scaling.z = radius * 2;
  78335. }
  78336. return mesh;
  78337. };
  78338. PhysicsViewer.prototype.dispose = function () {
  78339. for (var i = 0; i < this._numMeshes; i++) {
  78340. this.hideImpostor(this._impostors[i]);
  78341. }
  78342. if (this._debugBoxMesh) {
  78343. this._debugBoxMesh.dispose();
  78344. }
  78345. if (this._debugSphereMesh) {
  78346. this._debugSphereMesh.dispose();
  78347. }
  78348. if (this._debugMaterial) {
  78349. this._debugMaterial.dispose();
  78350. }
  78351. this._impostors.length = 0;
  78352. this._scene = null;
  78353. this._physicsEnginePlugin = null;
  78354. };
  78355. return PhysicsViewer;
  78356. }());
  78357. Debug.SkeletonViewer = /** @class */ (function () {
  78358. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  78359. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  78360. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  78361. this.skeleton = skeleton;
  78362. this.mesh = mesh;
  78363. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  78364. this.renderingGroupId = renderingGroupId;
  78365. this.color = BABYLON.Color3.White();
  78366. this._debugLines = new Array();
  78367. this._isEnabled = false;
  78368. this._scene = scene;
  78369. this.update();
  78370. this._renderFunction = this.update.bind(this);
  78371. }
  78372. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  78373. get: function () {
  78374. return this._isEnabled;
  78375. },
  78376. set: function (value) {
  78377. if (this._isEnabled === value) {
  78378. return;
  78379. }
  78380. this._isEnabled = value;
  78381. if (value) {
  78382. this._scene.registerBeforeRender(this._renderFunction);
  78383. }
  78384. else {
  78385. this._scene.unregisterBeforeRender(this._renderFunction);
  78386. }
  78387. },
  78388. enumerable: true,
  78389. configurable: true
  78390. });
  78391. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  78392. if (x === void 0) { x = 0; }
  78393. if (y === void 0) { y = 0; }
  78394. if (z === void 0) { z = 0; }
  78395. var tmat = BABYLON.Tmp.Matrix[0];
  78396. var parentBone = bone.getParent();
  78397. tmat.copyFrom(bone.getLocalMatrix());
  78398. if (x !== 0 || y !== 0 || z !== 0) {
  78399. var tmat2 = BABYLON.Tmp.Matrix[1];
  78400. BABYLON.Matrix.IdentityToRef(tmat2);
  78401. tmat2.m[12] = x;
  78402. tmat2.m[13] = y;
  78403. tmat2.m[14] = z;
  78404. tmat2.multiplyToRef(tmat, tmat);
  78405. }
  78406. if (parentBone) {
  78407. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  78408. }
  78409. tmat.multiplyToRef(meshMat, tmat);
  78410. position.x = tmat.m[12];
  78411. position.y = tmat.m[13];
  78412. position.z = tmat.m[14];
  78413. };
  78414. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  78415. var len = bones.length;
  78416. var meshPos = this.mesh.position;
  78417. for (var i = 0; i < len; i++) {
  78418. var bone = bones[i];
  78419. var points = this._debugLines[i];
  78420. if (!points) {
  78421. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78422. this._debugLines[i] = points;
  78423. }
  78424. this._getBonePosition(points[0], bone, meshMat);
  78425. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  78426. points[0].subtractInPlace(meshPos);
  78427. points[1].subtractInPlace(meshPos);
  78428. }
  78429. };
  78430. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  78431. var len = bones.length;
  78432. var boneNum = 0;
  78433. var meshPos = this.mesh.position;
  78434. for (var i = len - 1; i >= 0; i--) {
  78435. var childBone = bones[i];
  78436. var parentBone = childBone.getParent();
  78437. if (!parentBone) {
  78438. continue;
  78439. }
  78440. var points = this._debugLines[boneNum];
  78441. if (!points) {
  78442. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78443. this._debugLines[boneNum] = points;
  78444. }
  78445. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  78446. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  78447. points[0].subtractInPlace(meshPos);
  78448. points[1].subtractInPlace(meshPos);
  78449. boneNum++;
  78450. }
  78451. };
  78452. SkeletonViewer.prototype.update = function () {
  78453. if (this.autoUpdateBonesMatrices) {
  78454. this.skeleton.computeAbsoluteTransforms();
  78455. }
  78456. if (this.skeleton.bones[0].length === undefined) {
  78457. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  78458. }
  78459. else {
  78460. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  78461. }
  78462. if (!this._debugMesh) {
  78463. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  78464. this._debugMesh.renderingGroupId = this.renderingGroupId;
  78465. }
  78466. else {
  78467. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  78468. }
  78469. this._debugMesh.position.copyFrom(this.mesh.position);
  78470. this._debugMesh.color = this.color;
  78471. };
  78472. SkeletonViewer.prototype.dispose = function () {
  78473. if (this._debugMesh) {
  78474. this.isEnabled = false;
  78475. this._debugMesh.dispose();
  78476. this._debugMesh = null;
  78477. }
  78478. };
  78479. return SkeletonViewer;
  78480. }());
  78481. return Debug;
  78482. }());
  78483. BABYLON.Debug = Debug;
  78484. })(BABYLON || (BABYLON = {}));
  78485. //# sourceMappingURL=babylon.debugModules.js.map
  78486. var BABYLON;
  78487. (function (BABYLON) {
  78488. var RayHelper = /** @class */ (function () {
  78489. function RayHelper(ray) {
  78490. this.ray = ray;
  78491. }
  78492. RayHelper.CreateAndShow = function (ray, scene, color) {
  78493. var helper = new RayHelper(ray);
  78494. helper.show(scene, color);
  78495. return helper;
  78496. };
  78497. RayHelper.prototype.show = function (scene, color) {
  78498. if (!this._renderFunction && this.ray) {
  78499. var ray = this.ray;
  78500. this._renderFunction = this._render.bind(this);
  78501. this._scene = scene;
  78502. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  78503. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  78504. if (this._renderFunction) {
  78505. this._scene.registerBeforeRender(this._renderFunction);
  78506. }
  78507. }
  78508. if (color && this._renderLine) {
  78509. this._renderLine.color.copyFrom(color);
  78510. }
  78511. };
  78512. RayHelper.prototype.hide = function () {
  78513. if (this._renderFunction && this._scene) {
  78514. this._scene.unregisterBeforeRender(this._renderFunction);
  78515. this._scene = null;
  78516. this._renderFunction = null;
  78517. if (this._renderLine) {
  78518. this._renderLine.dispose();
  78519. this._renderLine = null;
  78520. }
  78521. this._renderPoints = [];
  78522. }
  78523. };
  78524. RayHelper.prototype._render = function () {
  78525. var ray = this.ray;
  78526. if (!ray) {
  78527. return;
  78528. }
  78529. var point = this._renderPoints[1];
  78530. var len = Math.min(ray.length, 1000000);
  78531. point.copyFrom(ray.direction);
  78532. point.scaleInPlace(len);
  78533. point.addInPlace(ray.origin);
  78534. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  78535. };
  78536. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  78537. this._attachedToMesh = mesh;
  78538. var ray = this.ray;
  78539. if (!ray) {
  78540. return;
  78541. }
  78542. if (!ray.direction) {
  78543. ray.direction = BABYLON.Vector3.Zero();
  78544. }
  78545. if (!ray.origin) {
  78546. ray.origin = BABYLON.Vector3.Zero();
  78547. }
  78548. if (length) {
  78549. ray.length = length;
  78550. }
  78551. if (!meshSpaceOrigin) {
  78552. meshSpaceOrigin = BABYLON.Vector3.Zero();
  78553. }
  78554. if (!meshSpaceDirection) {
  78555. // -1 so that this will work with Mesh.lookAt
  78556. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  78557. }
  78558. if (!this._meshSpaceDirection) {
  78559. this._meshSpaceDirection = meshSpaceDirection.clone();
  78560. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  78561. }
  78562. else {
  78563. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  78564. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  78565. }
  78566. if (!this._updateToMeshFunction) {
  78567. this._updateToMeshFunction = this._updateToMesh.bind(this);
  78568. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  78569. }
  78570. this._updateToMesh();
  78571. };
  78572. RayHelper.prototype.detachFromMesh = function () {
  78573. if (this._attachedToMesh) {
  78574. if (this._updateToMeshFunction) {
  78575. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  78576. }
  78577. this._attachedToMesh = null;
  78578. this._updateToMeshFunction = null;
  78579. }
  78580. };
  78581. RayHelper.prototype._updateToMesh = function () {
  78582. var ray = this.ray;
  78583. if (!this._attachedToMesh || !ray) {
  78584. return;
  78585. }
  78586. if (this._attachedToMesh._isDisposed) {
  78587. this.detachFromMesh();
  78588. return;
  78589. }
  78590. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  78591. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  78592. };
  78593. RayHelper.prototype.dispose = function () {
  78594. this.hide();
  78595. this.detachFromMesh();
  78596. this.ray = null;
  78597. };
  78598. return RayHelper;
  78599. }());
  78600. BABYLON.RayHelper = RayHelper;
  78601. })(BABYLON || (BABYLON = {}));
  78602. //# sourceMappingURL=babylon.rayHelper.js.map
  78603. var BABYLON;
  78604. (function (BABYLON) {
  78605. // load the inspector using require, if not present in the global namespace.
  78606. var DebugLayer = /** @class */ (function () {
  78607. function DebugLayer(scene) {
  78608. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  78609. this._scene = scene;
  78610. // load inspector using require, if it doesn't exist on the global namespace.
  78611. }
  78612. /** Creates the inspector window. */
  78613. DebugLayer.prototype._createInspector = function (config) {
  78614. if (config === void 0) { config = {}; }
  78615. var popup = config.popup || false;
  78616. var initialTab = config.initialTab || 0;
  78617. var parentElement = config.parentElement || null;
  78618. if (!this._inspector) {
  78619. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  78620. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  78621. } // else nothing to do,; instance is already existing
  78622. };
  78623. DebugLayer.prototype.isVisible = function () {
  78624. if (!this._inspector) {
  78625. return false;
  78626. }
  78627. return true;
  78628. };
  78629. DebugLayer.prototype.hide = function () {
  78630. if (this._inspector) {
  78631. try {
  78632. this._inspector.dispose();
  78633. }
  78634. catch (e) {
  78635. // If the inspector has been removed directly from the inspector tool
  78636. }
  78637. this._inspector = null;
  78638. }
  78639. };
  78640. DebugLayer.prototype.show = function (config) {
  78641. if (config === void 0) { config = {}; }
  78642. if (typeof this.BJSINSPECTOR == 'undefined') {
  78643. // Load inspector and add it to the DOM
  78644. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  78645. }
  78646. else {
  78647. // Otherwise creates the inspector
  78648. this._createInspector(config);
  78649. }
  78650. };
  78651. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  78652. return DebugLayer;
  78653. }());
  78654. BABYLON.DebugLayer = DebugLayer;
  78655. })(BABYLON || (BABYLON = {}));
  78656. //# sourceMappingURL=babylon.debugLayer.js.map
  78657. var BABYLON;
  78658. (function (BABYLON) {
  78659. var BoundingBoxRenderer = /** @class */ (function () {
  78660. function BoundingBoxRenderer(scene) {
  78661. this.frontColor = new BABYLON.Color3(1, 1, 1);
  78662. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  78663. this.showBackLines = true;
  78664. this.renderList = new BABYLON.SmartArray(32);
  78665. this._vertexBuffers = {};
  78666. this._scene = scene;
  78667. }
  78668. BoundingBoxRenderer.prototype._prepareRessources = function () {
  78669. if (this._colorShader) {
  78670. return;
  78671. }
  78672. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  78673. attributes: [BABYLON.VertexBuffer.PositionKind],
  78674. uniforms: ["world", "viewProjection", "color"]
  78675. });
  78676. var engine = this._scene.getEngine();
  78677. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  78678. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  78679. this._createIndexBuffer();
  78680. };
  78681. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  78682. var engine = this._scene.getEngine();
  78683. 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]);
  78684. };
  78685. BoundingBoxRenderer.prototype._rebuild = function () {
  78686. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78687. if (vb) {
  78688. vb._rebuild();
  78689. }
  78690. this._createIndexBuffer();
  78691. };
  78692. BoundingBoxRenderer.prototype.reset = function () {
  78693. this.renderList.reset();
  78694. };
  78695. BoundingBoxRenderer.prototype.render = function () {
  78696. if (this.renderList.length === 0) {
  78697. return;
  78698. }
  78699. this._prepareRessources();
  78700. if (!this._colorShader.isReady()) {
  78701. return;
  78702. }
  78703. var engine = this._scene.getEngine();
  78704. engine.setDepthWrite(false);
  78705. this._colorShader._preBind();
  78706. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  78707. var boundingBox = this.renderList.data[boundingBoxIndex];
  78708. var min = boundingBox.minimum;
  78709. var max = boundingBox.maximum;
  78710. var diff = max.subtract(min);
  78711. var median = min.add(diff.scale(0.5));
  78712. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  78713. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  78714. .multiply(boundingBox.getWorldMatrix());
  78715. // VBOs
  78716. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  78717. if (this.showBackLines) {
  78718. // Back
  78719. engine.setDepthFunctionToGreaterOrEqual();
  78720. this._scene.resetCachedMaterial();
  78721. this._colorShader.setColor4("color", this.backColor.toColor4());
  78722. this._colorShader.bind(worldMatrix);
  78723. // Draw order
  78724. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  78725. }
  78726. // Front
  78727. engine.setDepthFunctionToLess();
  78728. this._scene.resetCachedMaterial();
  78729. this._colorShader.setColor4("color", this.frontColor.toColor4());
  78730. this._colorShader.bind(worldMatrix);
  78731. // Draw order
  78732. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  78733. }
  78734. this._colorShader.unbind();
  78735. engine.setDepthFunctionToLessOrEqual();
  78736. engine.setDepthWrite(true);
  78737. };
  78738. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  78739. this._prepareRessources();
  78740. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  78741. return;
  78742. }
  78743. var engine = this._scene.getEngine();
  78744. engine.setDepthWrite(false);
  78745. engine.setColorWrite(false);
  78746. this._colorShader._preBind();
  78747. var boundingBox = mesh._boundingInfo.boundingBox;
  78748. var min = boundingBox.minimum;
  78749. var max = boundingBox.maximum;
  78750. var diff = max.subtract(min);
  78751. var median = min.add(diff.scale(0.5));
  78752. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  78753. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  78754. .multiply(boundingBox.getWorldMatrix());
  78755. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  78756. engine.setDepthFunctionToLess();
  78757. this._scene.resetCachedMaterial();
  78758. this._colorShader.bind(worldMatrix);
  78759. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  78760. this._colorShader.unbind();
  78761. engine.setDepthFunctionToLessOrEqual();
  78762. engine.setDepthWrite(true);
  78763. engine.setColorWrite(true);
  78764. };
  78765. BoundingBoxRenderer.prototype.dispose = function () {
  78766. if (!this._colorShader) {
  78767. return;
  78768. }
  78769. this.renderList.dispose();
  78770. this._colorShader.dispose();
  78771. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78772. if (buffer) {
  78773. buffer.dispose();
  78774. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  78775. }
  78776. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  78777. };
  78778. return BoundingBoxRenderer;
  78779. }());
  78780. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  78781. })(BABYLON || (BABYLON = {}));
  78782. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  78783. var BABYLON;
  78784. (function (BABYLON) {
  78785. var MorphTarget = /** @class */ (function () {
  78786. function MorphTarget(name, influence) {
  78787. if (influence === void 0) { influence = 0; }
  78788. this.name = name;
  78789. this.animations = new Array();
  78790. this._positions = null;
  78791. this._normals = null;
  78792. this._tangents = null;
  78793. this.onInfluenceChanged = new BABYLON.Observable();
  78794. this.influence = influence;
  78795. }
  78796. Object.defineProperty(MorphTarget.prototype, "influence", {
  78797. get: function () {
  78798. return this._influence;
  78799. },
  78800. set: function (influence) {
  78801. if (this._influence === influence) {
  78802. return;
  78803. }
  78804. var previous = this._influence;
  78805. this._influence = influence;
  78806. if (this.onInfluenceChanged.hasObservers) {
  78807. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  78808. }
  78809. },
  78810. enumerable: true,
  78811. configurable: true
  78812. });
  78813. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  78814. get: function () {
  78815. return !!this._positions;
  78816. },
  78817. enumerable: true,
  78818. configurable: true
  78819. });
  78820. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  78821. get: function () {
  78822. return !!this._normals;
  78823. },
  78824. enumerable: true,
  78825. configurable: true
  78826. });
  78827. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  78828. get: function () {
  78829. return !!this._tangents;
  78830. },
  78831. enumerable: true,
  78832. configurable: true
  78833. });
  78834. MorphTarget.prototype.setPositions = function (data) {
  78835. this._positions = data;
  78836. };
  78837. MorphTarget.prototype.getPositions = function () {
  78838. return this._positions;
  78839. };
  78840. MorphTarget.prototype.setNormals = function (data) {
  78841. this._normals = data;
  78842. };
  78843. MorphTarget.prototype.getNormals = function () {
  78844. return this._normals;
  78845. };
  78846. MorphTarget.prototype.setTangents = function (data) {
  78847. this._tangents = data;
  78848. };
  78849. MorphTarget.prototype.getTangents = function () {
  78850. return this._tangents;
  78851. };
  78852. /**
  78853. * Serializes the current target into a Serialization object.
  78854. * Returns the serialized object.
  78855. */
  78856. MorphTarget.prototype.serialize = function () {
  78857. var serializationObject = {};
  78858. serializationObject.name = this.name;
  78859. serializationObject.influence = this.influence;
  78860. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  78861. if (this.hasNormals) {
  78862. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  78863. }
  78864. if (this.hasTangents) {
  78865. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  78866. }
  78867. // Animations
  78868. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  78869. return serializationObject;
  78870. };
  78871. // Statics
  78872. MorphTarget.Parse = function (serializationObject) {
  78873. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  78874. result.setPositions(serializationObject.positions);
  78875. if (serializationObject.normals) {
  78876. result.setNormals(serializationObject.normals);
  78877. }
  78878. if (serializationObject.tangents) {
  78879. result.setTangents(serializationObject.tangents);
  78880. }
  78881. // Animations
  78882. if (serializationObject.animations) {
  78883. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  78884. var parsedAnimation = serializationObject.animations[animationIndex];
  78885. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  78886. }
  78887. }
  78888. return result;
  78889. };
  78890. MorphTarget.FromMesh = function (mesh, name, influence) {
  78891. if (!name) {
  78892. name = mesh.name;
  78893. }
  78894. var result = new MorphTarget(name, influence);
  78895. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  78896. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  78897. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  78898. }
  78899. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  78900. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  78901. }
  78902. return result;
  78903. };
  78904. return MorphTarget;
  78905. }());
  78906. BABYLON.MorphTarget = MorphTarget;
  78907. })(BABYLON || (BABYLON = {}));
  78908. //# sourceMappingURL=babylon.morphTarget.js.map
  78909. var BABYLON;
  78910. (function (BABYLON) {
  78911. var MorphTargetManager = /** @class */ (function () {
  78912. function MorphTargetManager(scene) {
  78913. if (scene === void 0) { scene = null; }
  78914. this._targets = new Array();
  78915. this._targetObservable = new Array();
  78916. this._activeTargets = new BABYLON.SmartArray(16);
  78917. this._supportsNormals = false;
  78918. this._supportsTangents = false;
  78919. this._vertexCount = 0;
  78920. this._uniqueId = 0;
  78921. this._tempInfluences = new Array();
  78922. if (!scene) {
  78923. scene = BABYLON.Engine.LastCreatedScene;
  78924. }
  78925. this._scene = scene;
  78926. if (this._scene) {
  78927. this._scene.morphTargetManagers.push(this);
  78928. this._uniqueId = this._scene.getUniqueId();
  78929. }
  78930. }
  78931. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  78932. get: function () {
  78933. return this._uniqueId;
  78934. },
  78935. enumerable: true,
  78936. configurable: true
  78937. });
  78938. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  78939. get: function () {
  78940. return this._vertexCount;
  78941. },
  78942. enumerable: true,
  78943. configurable: true
  78944. });
  78945. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  78946. get: function () {
  78947. return this._supportsNormals;
  78948. },
  78949. enumerable: true,
  78950. configurable: true
  78951. });
  78952. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  78953. get: function () {
  78954. return this._supportsTangents;
  78955. },
  78956. enumerable: true,
  78957. configurable: true
  78958. });
  78959. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  78960. get: function () {
  78961. return this._targets.length;
  78962. },
  78963. enumerable: true,
  78964. configurable: true
  78965. });
  78966. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  78967. get: function () {
  78968. return this._activeTargets.length;
  78969. },
  78970. enumerable: true,
  78971. configurable: true
  78972. });
  78973. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  78974. get: function () {
  78975. return this._influences;
  78976. },
  78977. enumerable: true,
  78978. configurable: true
  78979. });
  78980. MorphTargetManager.prototype.getActiveTarget = function (index) {
  78981. return this._activeTargets.data[index];
  78982. };
  78983. MorphTargetManager.prototype.getTarget = function (index) {
  78984. return this._targets[index];
  78985. };
  78986. MorphTargetManager.prototype.addTarget = function (target) {
  78987. var _this = this;
  78988. this._targets.push(target);
  78989. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  78990. _this._syncActiveTargets(needUpdate);
  78991. }));
  78992. this._syncActiveTargets(true);
  78993. };
  78994. MorphTargetManager.prototype.removeTarget = function (target) {
  78995. var index = this._targets.indexOf(target);
  78996. if (index >= 0) {
  78997. this._targets.splice(index, 1);
  78998. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  78999. this._syncActiveTargets(true);
  79000. }
  79001. };
  79002. /**
  79003. * Serializes the current manager into a Serialization object.
  79004. * Returns the serialized object.
  79005. */
  79006. MorphTargetManager.prototype.serialize = function () {
  79007. var serializationObject = {};
  79008. serializationObject.id = this.uniqueId;
  79009. serializationObject.targets = [];
  79010. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  79011. var target = _a[_i];
  79012. serializationObject.targets.push(target.serialize());
  79013. }
  79014. return serializationObject;
  79015. };
  79016. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  79017. var influenceCount = 0;
  79018. this._activeTargets.reset();
  79019. this._supportsNormals = true;
  79020. this._supportsTangents = true;
  79021. this._vertexCount = 0;
  79022. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  79023. var target = _a[_i];
  79024. this._activeTargets.push(target);
  79025. this._tempInfluences[influenceCount++] = target.influence;
  79026. var positions = target.getPositions();
  79027. if (positions) {
  79028. this._supportsNormals = this._supportsNormals && target.hasNormals;
  79029. this._supportsTangents = this._supportsTangents && target.hasTangents;
  79030. var vertexCount = positions.length / 3;
  79031. if (this._vertexCount === 0) {
  79032. this._vertexCount = vertexCount;
  79033. }
  79034. else if (this._vertexCount !== vertexCount) {
  79035. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  79036. return;
  79037. }
  79038. }
  79039. }
  79040. if (!this._influences || this._influences.length !== influenceCount) {
  79041. this._influences = new Float32Array(influenceCount);
  79042. }
  79043. for (var index = 0; index < influenceCount; index++) {
  79044. this._influences[index] = this._tempInfluences[index];
  79045. }
  79046. if (needUpdate && this._scene) {
  79047. // Flag meshes as dirty to resync with the active targets
  79048. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  79049. var mesh = _c[_b];
  79050. if (mesh.morphTargetManager === this) {
  79051. mesh._syncGeometryWithMorphTargetManager();
  79052. }
  79053. }
  79054. }
  79055. };
  79056. // Statics
  79057. MorphTargetManager.Parse = function (serializationObject, scene) {
  79058. var result = new MorphTargetManager(scene);
  79059. result._uniqueId = serializationObject.id;
  79060. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  79061. var targetData = _a[_i];
  79062. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  79063. }
  79064. return result;
  79065. };
  79066. return MorphTargetManager;
  79067. }());
  79068. BABYLON.MorphTargetManager = MorphTargetManager;
  79069. })(BABYLON || (BABYLON = {}));
  79070. //# sourceMappingURL=babylon.morphTargetManager.js.map
  79071. var BABYLON;
  79072. (function (BABYLON) {
  79073. var Octree = /** @class */ (function () {
  79074. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  79075. if (maxDepth === void 0) { maxDepth = 2; }
  79076. this.maxDepth = maxDepth;
  79077. this.dynamicContent = new Array();
  79078. this._maxBlockCapacity = maxBlockCapacity || 64;
  79079. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  79080. this._creationFunc = creationFunc;
  79081. }
  79082. // Methods
  79083. Octree.prototype.update = function (worldMin, worldMax, entries) {
  79084. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  79085. };
  79086. Octree.prototype.addMesh = function (entry) {
  79087. for (var index = 0; index < this.blocks.length; index++) {
  79088. var block = this.blocks[index];
  79089. block.addEntry(entry);
  79090. }
  79091. };
  79092. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  79093. this._selectionContent.reset();
  79094. for (var index = 0; index < this.blocks.length; index++) {
  79095. var block = this.blocks[index];
  79096. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  79097. }
  79098. if (allowDuplicate) {
  79099. this._selectionContent.concat(this.dynamicContent);
  79100. }
  79101. else {
  79102. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  79103. }
  79104. return this._selectionContent;
  79105. };
  79106. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  79107. this._selectionContent.reset();
  79108. for (var index = 0; index < this.blocks.length; index++) {
  79109. var block = this.blocks[index];
  79110. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  79111. }
  79112. if (allowDuplicate) {
  79113. this._selectionContent.concat(this.dynamicContent);
  79114. }
  79115. else {
  79116. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  79117. }
  79118. return this._selectionContent;
  79119. };
  79120. Octree.prototype.intersectsRay = function (ray) {
  79121. this._selectionContent.reset();
  79122. for (var index = 0; index < this.blocks.length; index++) {
  79123. var block = this.blocks[index];
  79124. block.intersectsRay(ray, this._selectionContent);
  79125. }
  79126. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  79127. return this._selectionContent;
  79128. };
  79129. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  79130. target.blocks = new Array();
  79131. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  79132. // Segmenting space
  79133. for (var x = 0; x < 2; x++) {
  79134. for (var y = 0; y < 2; y++) {
  79135. for (var z = 0; z < 2; z++) {
  79136. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  79137. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  79138. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  79139. block.addEntries(entries);
  79140. target.blocks.push(block);
  79141. }
  79142. }
  79143. }
  79144. };
  79145. Octree.CreationFuncForMeshes = function (entry, block) {
  79146. var boundingInfo = entry.getBoundingInfo();
  79147. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  79148. block.entries.push(entry);
  79149. }
  79150. };
  79151. Octree.CreationFuncForSubMeshes = function (entry, block) {
  79152. var boundingInfo = entry.getBoundingInfo();
  79153. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  79154. block.entries.push(entry);
  79155. }
  79156. };
  79157. return Octree;
  79158. }());
  79159. BABYLON.Octree = Octree;
  79160. })(BABYLON || (BABYLON = {}));
  79161. //# sourceMappingURL=babylon.octree.js.map
  79162. var BABYLON;
  79163. (function (BABYLON) {
  79164. var OctreeBlock = /** @class */ (function () {
  79165. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  79166. this.entries = new Array();
  79167. this._boundingVectors = new Array();
  79168. this._capacity = capacity;
  79169. this._depth = depth;
  79170. this._maxDepth = maxDepth;
  79171. this._creationFunc = creationFunc;
  79172. this._minPoint = minPoint;
  79173. this._maxPoint = maxPoint;
  79174. this._boundingVectors.push(minPoint.clone());
  79175. this._boundingVectors.push(maxPoint.clone());
  79176. this._boundingVectors.push(minPoint.clone());
  79177. this._boundingVectors[2].x = maxPoint.x;
  79178. this._boundingVectors.push(minPoint.clone());
  79179. this._boundingVectors[3].y = maxPoint.y;
  79180. this._boundingVectors.push(minPoint.clone());
  79181. this._boundingVectors[4].z = maxPoint.z;
  79182. this._boundingVectors.push(maxPoint.clone());
  79183. this._boundingVectors[5].z = minPoint.z;
  79184. this._boundingVectors.push(maxPoint.clone());
  79185. this._boundingVectors[6].x = minPoint.x;
  79186. this._boundingVectors.push(maxPoint.clone());
  79187. this._boundingVectors[7].y = minPoint.y;
  79188. }
  79189. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  79190. // Property
  79191. get: function () {
  79192. return this._capacity;
  79193. },
  79194. enumerable: true,
  79195. configurable: true
  79196. });
  79197. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  79198. get: function () {
  79199. return this._minPoint;
  79200. },
  79201. enumerable: true,
  79202. configurable: true
  79203. });
  79204. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  79205. get: function () {
  79206. return this._maxPoint;
  79207. },
  79208. enumerable: true,
  79209. configurable: true
  79210. });
  79211. // Methods
  79212. OctreeBlock.prototype.addEntry = function (entry) {
  79213. if (this.blocks) {
  79214. for (var index = 0; index < this.blocks.length; index++) {
  79215. var block = this.blocks[index];
  79216. block.addEntry(entry);
  79217. }
  79218. return;
  79219. }
  79220. this._creationFunc(entry, this);
  79221. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  79222. this.createInnerBlocks();
  79223. }
  79224. };
  79225. OctreeBlock.prototype.addEntries = function (entries) {
  79226. for (var index = 0; index < entries.length; index++) {
  79227. var mesh = entries[index];
  79228. this.addEntry(mesh);
  79229. }
  79230. };
  79231. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  79232. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  79233. if (this.blocks) {
  79234. for (var index = 0; index < this.blocks.length; index++) {
  79235. var block = this.blocks[index];
  79236. block.select(frustumPlanes, selection, allowDuplicate);
  79237. }
  79238. return;
  79239. }
  79240. if (allowDuplicate) {
  79241. selection.concat(this.entries);
  79242. }
  79243. else {
  79244. selection.concatWithNoDuplicate(this.entries);
  79245. }
  79246. }
  79247. };
  79248. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  79249. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  79250. if (this.blocks) {
  79251. for (var index = 0; index < this.blocks.length; index++) {
  79252. var block = this.blocks[index];
  79253. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  79254. }
  79255. return;
  79256. }
  79257. if (allowDuplicate) {
  79258. selection.concat(this.entries);
  79259. }
  79260. else {
  79261. selection.concatWithNoDuplicate(this.entries);
  79262. }
  79263. }
  79264. };
  79265. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  79266. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  79267. if (this.blocks) {
  79268. for (var index = 0; index < this.blocks.length; index++) {
  79269. var block = this.blocks[index];
  79270. block.intersectsRay(ray, selection);
  79271. }
  79272. return;
  79273. }
  79274. selection.concatWithNoDuplicate(this.entries);
  79275. }
  79276. };
  79277. OctreeBlock.prototype.createInnerBlocks = function () {
  79278. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  79279. };
  79280. return OctreeBlock;
  79281. }());
  79282. BABYLON.OctreeBlock = OctreeBlock;
  79283. })(BABYLON || (BABYLON = {}));
  79284. //# sourceMappingURL=babylon.octreeBlock.js.map
  79285. var BABYLON;
  79286. (function (BABYLON) {
  79287. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  79288. __extends(VRDistortionCorrectionPostProcess, _super);
  79289. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  79290. var _this = _super.call(this, name, "vrDistortionCorrection", [
  79291. 'LensCenter',
  79292. 'Scale',
  79293. 'ScaleIn',
  79294. 'HmdWarpParam'
  79295. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  79296. _this._isRightEye = isRightEye;
  79297. _this._distortionFactors = vrMetrics.distortionK;
  79298. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  79299. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  79300. _this.adaptScaleToCurrentViewport = true;
  79301. _this.onSizeChangedObservable.add(function () {
  79302. _this.aspectRatio = _this.width * .5 / _this.height;
  79303. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  79304. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  79305. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  79306. });
  79307. _this.onApplyObservable.add(function (effect) {
  79308. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  79309. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  79310. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  79311. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  79312. });
  79313. return _this;
  79314. }
  79315. return VRDistortionCorrectionPostProcess;
  79316. }(BABYLON.PostProcess));
  79317. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  79318. })(BABYLON || (BABYLON = {}));
  79319. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  79320. var BABYLON;
  79321. (function (BABYLON) {
  79322. var AnaglyphPostProcess = /** @class */ (function (_super) {
  79323. __extends(AnaglyphPostProcess, _super);
  79324. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  79325. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  79326. _this._passedProcess = rigCameras[0]._rigPostProcess;
  79327. _this.onApplyObservable.add(function (effect) {
  79328. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  79329. });
  79330. return _this;
  79331. }
  79332. return AnaglyphPostProcess;
  79333. }(BABYLON.PostProcess));
  79334. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  79335. })(BABYLON || (BABYLON = {}));
  79336. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  79337. var BABYLON;
  79338. (function (BABYLON) {
  79339. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  79340. __extends(StereoscopicInterlacePostProcess, _super);
  79341. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  79342. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  79343. _this._passedProcess = rigCameras[0]._rigPostProcess;
  79344. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  79345. _this.onSizeChangedObservable.add(function () {
  79346. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  79347. });
  79348. _this.onApplyObservable.add(function (effect) {
  79349. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  79350. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  79351. });
  79352. return _this;
  79353. }
  79354. return StereoscopicInterlacePostProcess;
  79355. }(BABYLON.PostProcess));
  79356. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  79357. })(BABYLON || (BABYLON = {}));
  79358. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  79359. var BABYLON;
  79360. (function (BABYLON) {
  79361. /**
  79362. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  79363. * Screen rotation is taken into account.
  79364. */
  79365. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  79366. function FreeCameraDeviceOrientationInput() {
  79367. var _this = this;
  79368. this._screenOrientationAngle = 0;
  79369. this._screenQuaternion = new BABYLON.Quaternion();
  79370. this._alpha = 0;
  79371. this._beta = 0;
  79372. this._gamma = 0;
  79373. this._orientationChanged = function () {
  79374. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  79375. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  79376. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  79377. };
  79378. this._deviceOrientation = function (evt) {
  79379. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  79380. _this._beta = evt.beta !== null ? evt.beta : 0;
  79381. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  79382. };
  79383. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  79384. this._orientationChanged();
  79385. }
  79386. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  79387. get: function () {
  79388. return this._camera;
  79389. },
  79390. set: function (camera) {
  79391. this._camera = camera;
  79392. if (this._camera != null && !this._camera.rotationQuaternion) {
  79393. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  79394. }
  79395. },
  79396. enumerable: true,
  79397. configurable: true
  79398. });
  79399. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  79400. window.addEventListener("orientationchange", this._orientationChanged);
  79401. window.addEventListener("deviceorientation", this._deviceOrientation);
  79402. //In certain cases, the attach control is called AFTER orientation was changed,
  79403. //So this is needed.
  79404. this._orientationChanged();
  79405. };
  79406. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  79407. window.removeEventListener("orientationchange", this._orientationChanged);
  79408. window.removeEventListener("deviceorientation", this._deviceOrientation);
  79409. };
  79410. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  79411. //if no device orientation provided, don't update the rotation.
  79412. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  79413. if (!this._alpha)
  79414. return;
  79415. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  79416. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  79417. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  79418. //Mirror on XY Plane
  79419. this._camera.rotationQuaternion.z *= -1;
  79420. this._camera.rotationQuaternion.w *= -1;
  79421. };
  79422. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  79423. return "FreeCameraDeviceOrientationInput";
  79424. };
  79425. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  79426. return "deviceOrientation";
  79427. };
  79428. return FreeCameraDeviceOrientationInput;
  79429. }());
  79430. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  79431. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  79432. })(BABYLON || (BABYLON = {}));
  79433. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  79434. var BABYLON;
  79435. (function (BABYLON) {
  79436. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  79437. function ArcRotateCameraVRDeviceOrientationInput() {
  79438. this.alphaCorrection = 1;
  79439. this.betaCorrection = 1;
  79440. this.gammaCorrection = 1;
  79441. this._alpha = 0;
  79442. this._gamma = 0;
  79443. this._dirty = false;
  79444. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  79445. }
  79446. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  79447. this.camera.attachControl(element, noPreventDefault);
  79448. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  79449. };
  79450. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  79451. if (evt.alpha !== null) {
  79452. this._alpha = +evt.alpha | 0;
  79453. }
  79454. if (evt.gamma !== null) {
  79455. this._gamma = +evt.gamma | 0;
  79456. }
  79457. this._dirty = true;
  79458. };
  79459. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  79460. if (this._dirty) {
  79461. this._dirty = false;
  79462. if (this._gamma < 0) {
  79463. this._gamma = 180 + this._gamma;
  79464. }
  79465. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  79466. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  79467. }
  79468. };
  79469. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  79470. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  79471. };
  79472. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  79473. return "ArcRotateCameraVRDeviceOrientationInput";
  79474. };
  79475. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  79476. return "VRDeviceOrientation";
  79477. };
  79478. return ArcRotateCameraVRDeviceOrientationInput;
  79479. }());
  79480. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  79481. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  79482. })(BABYLON || (BABYLON = {}));
  79483. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  79484. var BABYLON;
  79485. (function (BABYLON) {
  79486. var VRCameraMetrics = /** @class */ (function () {
  79487. function VRCameraMetrics() {
  79488. this.compensateDistortion = true;
  79489. }
  79490. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  79491. get: function () {
  79492. return this.hResolution / (2 * this.vResolution);
  79493. },
  79494. enumerable: true,
  79495. configurable: true
  79496. });
  79497. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  79498. get: function () {
  79499. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  79500. },
  79501. enumerable: true,
  79502. configurable: true
  79503. });
  79504. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  79505. get: function () {
  79506. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  79507. var h = (4 * meters) / this.hScreenSize;
  79508. return BABYLON.Matrix.Translation(h, 0, 0);
  79509. },
  79510. enumerable: true,
  79511. configurable: true
  79512. });
  79513. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  79514. get: function () {
  79515. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  79516. var h = (4 * meters) / this.hScreenSize;
  79517. return BABYLON.Matrix.Translation(-h, 0, 0);
  79518. },
  79519. enumerable: true,
  79520. configurable: true
  79521. });
  79522. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  79523. get: function () {
  79524. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  79525. },
  79526. enumerable: true,
  79527. configurable: true
  79528. });
  79529. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  79530. get: function () {
  79531. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  79532. },
  79533. enumerable: true,
  79534. configurable: true
  79535. });
  79536. VRCameraMetrics.GetDefault = function () {
  79537. var result = new VRCameraMetrics();
  79538. result.hResolution = 1280;
  79539. result.vResolution = 800;
  79540. result.hScreenSize = 0.149759993;
  79541. result.vScreenSize = 0.0935999975;
  79542. result.vScreenCenter = 0.0467999987;
  79543. result.eyeToScreenDistance = 0.0410000011;
  79544. result.lensSeparationDistance = 0.0635000020;
  79545. result.interpupillaryDistance = 0.0640000030;
  79546. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  79547. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  79548. result.postProcessScaleFactor = 1.714605507808412;
  79549. result.lensCenterOffset = 0.151976421;
  79550. return result;
  79551. };
  79552. return VRCameraMetrics;
  79553. }());
  79554. BABYLON.VRCameraMetrics = VRCameraMetrics;
  79555. })(BABYLON || (BABYLON = {}));
  79556. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  79557. var BABYLON;
  79558. (function (BABYLON) {
  79559. /**
  79560. * This represents a WebVR camera.
  79561. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  79562. * @example http://doc.babylonjs.com/how_to/webvr_camera
  79563. */
  79564. var WebVRFreeCamera = /** @class */ (function (_super) {
  79565. __extends(WebVRFreeCamera, _super);
  79566. /**
  79567. * Instantiates a WebVRFreeCamera.
  79568. * @param name The name of the WebVRFreeCamera
  79569. * @param position The starting anchor position for the camera
  79570. * @param scene The scene the camera belongs to
  79571. * @param webVROptions a set of customizable options for the webVRCamera
  79572. */
  79573. function WebVRFreeCamera(name, position, scene, webVROptions) {
  79574. if (webVROptions === void 0) { webVROptions = {}; }
  79575. var _this = _super.call(this, name, position, scene) || this;
  79576. _this.webVROptions = webVROptions;
  79577. /**
  79578. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  79579. */
  79580. _this._vrDevice = null;
  79581. /**
  79582. * The rawPose of the vrDevice.
  79583. */
  79584. _this.rawPose = null;
  79585. _this._specsVersion = "1.1";
  79586. _this._attached = false;
  79587. _this._descendants = [];
  79588. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  79589. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  79590. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  79591. _this._standingMatrix = null;
  79592. /**
  79593. * Represents device position in babylon space.
  79594. */
  79595. _this.devicePosition = BABYLON.Vector3.Zero();
  79596. /**
  79597. * Represents device rotation in babylon space.
  79598. */
  79599. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  79600. /**
  79601. * The scale of the device to be used when translating from device space to babylon space.
  79602. */
  79603. _this.deviceScaleFactor = 1;
  79604. _this._deviceToWorld = BABYLON.Matrix.Identity();
  79605. _this._worldToDevice = BABYLON.Matrix.Identity();
  79606. /**
  79607. * References to the webVR controllers for the vrDevice.
  79608. */
  79609. _this.controllers = [];
  79610. /**
  79611. * Emits an event when a controller is attached.
  79612. */
  79613. _this.onControllersAttachedObservable = new BABYLON.Observable();
  79614. /**
  79615. * Emits an event when a controller's mesh has been loaded;
  79616. */
  79617. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  79618. /**
  79619. * If the rig cameras be used as parent instead of this camera.
  79620. */
  79621. _this.rigParenting = true;
  79622. _this._defaultHeight = undefined;
  79623. _this._workingVector = BABYLON.Vector3.Zero();
  79624. _this._oneVector = BABYLON.Vector3.One();
  79625. _this._workingMatrix = BABYLON.Matrix.Identity();
  79626. _this._cache.position = BABYLON.Vector3.Zero();
  79627. if (webVROptions.defaultHeight) {
  79628. _this._defaultHeight = webVROptions.defaultHeight;
  79629. _this.position.y = _this._defaultHeight;
  79630. }
  79631. _this.minZ = 0.1;
  79632. //legacy support - the compensation boolean was removed.
  79633. if (arguments.length === 5) {
  79634. _this.webVROptions = arguments[4];
  79635. }
  79636. // default webVR options
  79637. if (_this.webVROptions.trackPosition == undefined) {
  79638. _this.webVROptions.trackPosition = true;
  79639. }
  79640. if (_this.webVROptions.controllerMeshes == undefined) {
  79641. _this.webVROptions.controllerMeshes = true;
  79642. }
  79643. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  79644. _this.webVROptions.defaultLightingOnControllers = true;
  79645. }
  79646. _this.rotationQuaternion = new BABYLON.Quaternion();
  79647. if (_this.webVROptions && _this.webVROptions.positionScale) {
  79648. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  79649. }
  79650. //enable VR
  79651. var engine = _this.getEngine();
  79652. _this._onVREnabled = function (success) { if (success) {
  79653. _this.initControllers();
  79654. } };
  79655. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  79656. engine.initWebVR().add(function (event) {
  79657. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  79658. return;
  79659. }
  79660. _this._vrDevice = event.vrDisplay;
  79661. //reset the rig parameters.
  79662. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  79663. if (_this._attached) {
  79664. _this.getEngine().enableVR();
  79665. }
  79666. });
  79667. if (typeof (VRFrameData) !== "undefined")
  79668. _this._frameData = new VRFrameData();
  79669. /**
  79670. * The idea behind the following lines:
  79671. * objects that have the camera as parent should actually have the rig cameras as a parent.
  79672. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  79673. * the second will not show it correctly.
  79674. *
  79675. * To solve this - each object that has the camera as parent will be added to a protected array.
  79676. * When the rig camera renders, it will take this array and set all of those to be its children.
  79677. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  79678. * Amazing!
  79679. */
  79680. scene.onBeforeCameraRenderObservable.add(function (camera) {
  79681. if (camera.parent === _this && _this.rigParenting) {
  79682. _this._descendants = _this.getDescendants(true, function (n) {
  79683. // don't take the cameras or the controllers!
  79684. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  79685. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  79686. return !isController && !isRigCamera;
  79687. });
  79688. _this._descendants.forEach(function (node) {
  79689. node.parent = camera;
  79690. });
  79691. }
  79692. });
  79693. scene.onAfterCameraRenderObservable.add(function (camera) {
  79694. if (camera.parent === _this && _this.rigParenting) {
  79695. _this._descendants.forEach(function (node) {
  79696. node.parent = _this;
  79697. });
  79698. }
  79699. });
  79700. return _this;
  79701. }
  79702. /**
  79703. * Gets the device distance from the ground in meters.
  79704. * @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.
  79705. */
  79706. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  79707. if (this._standingMatrix) {
  79708. // Add standing matrix offset to get real offset from ground in room
  79709. this._standingMatrix.getTranslationToRef(this._workingVector);
  79710. return this._deviceRoomPosition.y + this._workingVector.y;
  79711. }
  79712. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  79713. return this._defaultHeight || 0;
  79714. };
  79715. /**
  79716. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  79717. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  79718. */
  79719. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  79720. var _this = this;
  79721. if (callback === void 0) { callback = function (bool) { }; }
  79722. // Use standing matrix if available
  79723. this.getEngine().initWebVRAsync().then(function (result) {
  79724. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  79725. callback(false);
  79726. }
  79727. else {
  79728. _this._standingMatrix = new BABYLON.Matrix();
  79729. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  79730. if (!_this.getScene().useRightHandedSystem) {
  79731. [2, 6, 8, 9, 14].forEach(function (num) {
  79732. if (_this._standingMatrix) {
  79733. _this._standingMatrix.m[num] *= -1;
  79734. }
  79735. });
  79736. }
  79737. callback(true);
  79738. }
  79739. });
  79740. };
  79741. /**
  79742. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  79743. * @returns A promise with a boolean set to if the standing matrix is supported.
  79744. */
  79745. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  79746. var _this = this;
  79747. return new Promise(function (res, rej) {
  79748. _this.useStandingMatrix(function (supported) {
  79749. res(supported);
  79750. });
  79751. });
  79752. };
  79753. /**
  79754. * Disposes the camera
  79755. */
  79756. WebVRFreeCamera.prototype.dispose = function () {
  79757. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  79758. _super.prototype.dispose.call(this);
  79759. };
  79760. /**
  79761. * Gets a vrController by name.
  79762. * @param name The name of the controller to retreive
  79763. * @returns the controller matching the name specified or null if not found
  79764. */
  79765. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  79766. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  79767. var gp = _a[_i];
  79768. if (gp.hand === name) {
  79769. return gp;
  79770. }
  79771. }
  79772. return null;
  79773. };
  79774. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  79775. /**
  79776. * The controller corrisponding to the users left hand.
  79777. */
  79778. get: function () {
  79779. if (!this._leftController) {
  79780. this._leftController = this.getControllerByName("left");
  79781. }
  79782. return this._leftController;
  79783. },
  79784. enumerable: true,
  79785. configurable: true
  79786. });
  79787. ;
  79788. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  79789. /**
  79790. * The controller corrisponding to the users right hand.
  79791. */
  79792. get: function () {
  79793. if (!this._rightController) {
  79794. this._rightController = this.getControllerByName("right");
  79795. }
  79796. return this._rightController;
  79797. },
  79798. enumerable: true,
  79799. configurable: true
  79800. });
  79801. ;
  79802. /**
  79803. * Casts a ray forward from the vrCamera's gaze.
  79804. * @param length Length of the ray (default: 100)
  79805. * @returns the ray corrisponding to the gaze
  79806. */
  79807. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  79808. if (length === void 0) { length = 100; }
  79809. if (this.leftCamera) {
  79810. // Use left eye to avoid computation to compute center on every call
  79811. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  79812. }
  79813. else {
  79814. return _super.prototype.getForwardRay.call(this, length);
  79815. }
  79816. };
  79817. /**
  79818. * Updates the camera based on device's frame data
  79819. */
  79820. WebVRFreeCamera.prototype._checkInputs = function () {
  79821. if (this._vrDevice && this._vrDevice.isPresenting) {
  79822. this._vrDevice.getFrameData(this._frameData);
  79823. this.updateFromDevice(this._frameData.pose);
  79824. }
  79825. _super.prototype._checkInputs.call(this);
  79826. };
  79827. /**
  79828. * Updates the poseControlled values based on the input device pose.
  79829. * @param poseData Pose coming from the device
  79830. */
  79831. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  79832. if (poseData && poseData.orientation) {
  79833. this.rawPose = poseData;
  79834. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  79835. if (this.getScene().useRightHandedSystem) {
  79836. this._deviceRoomRotationQuaternion.z *= -1;
  79837. this._deviceRoomRotationQuaternion.w *= -1;
  79838. }
  79839. if (this.webVROptions.trackPosition && this.rawPose.position) {
  79840. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  79841. if (this.getScene().useRightHandedSystem) {
  79842. this._deviceRoomPosition.z *= -1;
  79843. }
  79844. }
  79845. }
  79846. };
  79847. /**
  79848. * WebVR's attach control will start broadcasting frames to the device.
  79849. * Note that in certain browsers (chrome for example) this function must be called
  79850. * within a user-interaction callback. Example:
  79851. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  79852. *
  79853. * @param element html element to attach the vrDevice to
  79854. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  79855. */
  79856. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  79857. _super.prototype.attachControl.call(this, element, noPreventDefault);
  79858. this._attached = true;
  79859. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  79860. if (this._vrDevice) {
  79861. this.getEngine().enableVR();
  79862. }
  79863. };
  79864. /**
  79865. * Detaches the camera from the html element and disables VR
  79866. *
  79867. * @param element html element to detach from
  79868. */
  79869. WebVRFreeCamera.prototype.detachControl = function (element) {
  79870. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  79871. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  79872. _super.prototype.detachControl.call(this, element);
  79873. this._attached = false;
  79874. this.getEngine().disableVR();
  79875. };
  79876. /**
  79877. * @returns the name of this class
  79878. */
  79879. WebVRFreeCamera.prototype.getClassName = function () {
  79880. return "WebVRFreeCamera";
  79881. };
  79882. /**
  79883. * Calls resetPose on the vrDisplay
  79884. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  79885. */
  79886. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  79887. //uses the vrDisplay's "resetPose()".
  79888. //pitch and roll won't be affected.
  79889. this._vrDevice.resetPose();
  79890. };
  79891. /**
  79892. * Updates the rig cameras (left and right eye)
  79893. */
  79894. WebVRFreeCamera.prototype._updateRigCameras = function () {
  79895. var camLeft = this._rigCameras[0];
  79896. var camRight = this._rigCameras[1];
  79897. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  79898. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  79899. camLeft.position.copyFrom(this._deviceRoomPosition);
  79900. camRight.position.copyFrom(this._deviceRoomPosition);
  79901. };
  79902. /**
  79903. * Updates the cached values of the camera
  79904. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  79905. */
  79906. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  79907. var _this = this;
  79908. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  79909. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  79910. if (!this.updateCacheCalled) {
  79911. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  79912. this.updateCacheCalled = true;
  79913. this.update();
  79914. }
  79915. // Set working vector to the device position in room space rotated by the new rotation
  79916. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  79917. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  79918. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  79919. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  79920. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  79921. // Add translation from anchor position
  79922. this._deviceToWorld.getTranslationToRef(this._workingVector);
  79923. this._workingVector.addInPlace(this.position);
  79924. this._workingVector.subtractInPlace(this._cache.position);
  79925. this._deviceToWorld.setTranslation(this._workingVector);
  79926. // Set an inverted matrix to be used when updating the camera
  79927. this._deviceToWorld.invertToRef(this._worldToDevice);
  79928. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  79929. this.controllers.forEach(function (controller) {
  79930. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  79931. controller.update();
  79932. });
  79933. }
  79934. if (!ignoreParentClass) {
  79935. _super.prototype._updateCache.call(this);
  79936. }
  79937. this.updateCacheCalled = false;
  79938. };
  79939. /**
  79940. * Updates the current device position and rotation in the babylon world
  79941. */
  79942. WebVRFreeCamera.prototype.update = function () {
  79943. // Get current device position in babylon world
  79944. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  79945. // Get current device rotation in babylon world
  79946. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  79947. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  79948. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  79949. _super.prototype.update.call(this);
  79950. };
  79951. /**
  79952. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  79953. * @returns an identity matrix
  79954. */
  79955. WebVRFreeCamera.prototype._getViewMatrix = function () {
  79956. return BABYLON.Matrix.Identity();
  79957. };
  79958. /**
  79959. * This function is called by the two RIG cameras.
  79960. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  79961. */
  79962. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  79963. var _this = this;
  79964. // Update the parent camera prior to using a child camera to avoid desynchronization
  79965. var parentCamera = this._cameraRigParams["parentCamera"];
  79966. parentCamera._updateCache();
  79967. //WebVR 1.1
  79968. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  79969. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  79970. if (!this.getScene().useRightHandedSystem) {
  79971. [2, 6, 8, 9, 14].forEach(function (num) {
  79972. _this._webvrViewMatrix.m[num] *= -1;
  79973. });
  79974. }
  79975. // update the camera rotation matrix
  79976. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  79977. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  79978. // Computing target and final matrix
  79979. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  79980. // should the view matrix be updated with scale and position offset?
  79981. if (parentCamera.deviceScaleFactor !== 1) {
  79982. this._webvrViewMatrix.invert();
  79983. // scale the position, if set
  79984. if (parentCamera.deviceScaleFactor) {
  79985. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  79986. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  79987. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  79988. }
  79989. this._webvrViewMatrix.invert();
  79990. }
  79991. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  79992. return this._webvrViewMatrix;
  79993. };
  79994. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  79995. var _this = this;
  79996. var parentCamera = this.parent;
  79997. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  79998. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  79999. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  80000. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  80001. //babylon compatible matrix
  80002. if (!this.getScene().useRightHandedSystem) {
  80003. [8, 9, 10, 11].forEach(function (num) {
  80004. _this._projectionMatrix.m[num] *= -1;
  80005. });
  80006. }
  80007. return this._projectionMatrix;
  80008. };
  80009. /**
  80010. * Initializes the controllers and their meshes
  80011. */
  80012. WebVRFreeCamera.prototype.initControllers = function () {
  80013. var _this = this;
  80014. this.controllers = [];
  80015. var manager = this.getScene().gamepadManager;
  80016. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  80017. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  80018. var webVrController = gamepad;
  80019. if (webVrController.defaultModel) {
  80020. webVrController.defaultModel.setEnabled(false);
  80021. }
  80022. if (webVrController.hand === "right") {
  80023. _this._rightController = null;
  80024. }
  80025. if (webVrController.hand === "left") {
  80026. _this._leftController = null;
  80027. }
  80028. var controllerIndex = _this.controllers.indexOf(webVrController);
  80029. if (controllerIndex !== -1) {
  80030. _this.controllers.splice(controllerIndex, 1);
  80031. }
  80032. }
  80033. });
  80034. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  80035. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  80036. var webVrController_1 = gamepad;
  80037. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  80038. if (_this.webVROptions.controllerMeshes) {
  80039. if (webVrController_1.defaultModel) {
  80040. webVrController_1.defaultModel.setEnabled(true);
  80041. }
  80042. else {
  80043. // Load the meshes
  80044. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  80045. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  80046. if (_this.webVROptions.defaultLightingOnControllers) {
  80047. if (!_this._lightOnControllers) {
  80048. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  80049. }
  80050. var activateLightOnSubMeshes_1 = function (mesh, light) {
  80051. var children = mesh.getChildren();
  80052. if (children.length !== 0) {
  80053. children.forEach(function (mesh) {
  80054. light.includedOnlyMeshes.push(mesh);
  80055. activateLightOnSubMeshes_1(mesh, light);
  80056. });
  80057. }
  80058. };
  80059. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  80060. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  80061. }
  80062. });
  80063. }
  80064. }
  80065. webVrController_1.attachToPoseControlledCamera(_this);
  80066. // since this is async - sanity check. Is the controller already stored?
  80067. if (_this.controllers.indexOf(webVrController_1) === -1) {
  80068. //add to the controllers array
  80069. _this.controllers.push(webVrController_1);
  80070. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  80071. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  80072. // So we're overriding setting left & right manually to be sure
  80073. var firstViveWandDetected = false;
  80074. for (var i = 0; i < _this.controllers.length; i++) {
  80075. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  80076. if (!firstViveWandDetected) {
  80077. firstViveWandDetected = true;
  80078. _this.controllers[i].hand = "left";
  80079. }
  80080. else {
  80081. _this.controllers[i].hand = "right";
  80082. }
  80083. }
  80084. }
  80085. //did we find enough controllers? Great! let the developer know.
  80086. if (_this.controllers.length >= 2) {
  80087. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  80088. }
  80089. }
  80090. }
  80091. });
  80092. };
  80093. return WebVRFreeCamera;
  80094. }(BABYLON.FreeCamera));
  80095. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  80096. })(BABYLON || (BABYLON = {}));
  80097. //# sourceMappingURL=babylon.webVRCamera.js.map
  80098. var BABYLON;
  80099. (function (BABYLON) {
  80100. // We're mainly based on the logic defined into the FreeCamera code
  80101. /**
  80102. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  80103. * being tilted forward or back and left or right.
  80104. */
  80105. var DeviceOrientationCamera = /** @class */ (function (_super) {
  80106. __extends(DeviceOrientationCamera, _super);
  80107. /**
  80108. * Creates a new device orientation camera. @see DeviceOrientationCamera
  80109. * @param name The name of the camera
  80110. * @param position The start position camera
  80111. * @param scene The scene the camera belongs to
  80112. */
  80113. function DeviceOrientationCamera(name, position, scene) {
  80114. var _this = _super.call(this, name, position, scene) || this;
  80115. _this._quaternionCache = new BABYLON.Quaternion();
  80116. _this.inputs.addDeviceOrientation();
  80117. return _this;
  80118. }
  80119. /**
  80120. * Gets the current instance class name ("DeviceOrientationCamera").
  80121. * This helps avoiding instanceof at run time.
  80122. * @returns the class name
  80123. */
  80124. DeviceOrientationCamera.prototype.getClassName = function () {
  80125. return "DeviceOrientationCamera";
  80126. };
  80127. /**
  80128. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  80129. */
  80130. DeviceOrientationCamera.prototype._checkInputs = function () {
  80131. _super.prototype._checkInputs.call(this);
  80132. this._quaternionCache.copyFrom(this.rotationQuaternion);
  80133. if (this._initialQuaternion) {
  80134. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  80135. }
  80136. };
  80137. /**
  80138. * Reset the camera to its default orientation on the specified axis only.
  80139. * @param axis The axis to reset
  80140. */
  80141. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  80142. var _this = this;
  80143. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  80144. //can only work if this camera has a rotation quaternion already.
  80145. if (!this.rotationQuaternion)
  80146. return;
  80147. if (!this._initialQuaternion) {
  80148. this._initialQuaternion = new BABYLON.Quaternion();
  80149. }
  80150. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  80151. ['x', 'y', 'z'].forEach(function (axisName) {
  80152. if (!axis[axisName]) {
  80153. _this._initialQuaternion[axisName] = 0;
  80154. }
  80155. else {
  80156. _this._initialQuaternion[axisName] *= -1;
  80157. }
  80158. });
  80159. this._initialQuaternion.normalize();
  80160. //force rotation update
  80161. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  80162. };
  80163. return DeviceOrientationCamera;
  80164. }(BABYLON.FreeCamera));
  80165. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  80166. })(BABYLON || (BABYLON = {}));
  80167. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  80168. var BABYLON;
  80169. (function (BABYLON) {
  80170. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  80171. __extends(VRDeviceOrientationFreeCamera, _super);
  80172. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  80173. if (compensateDistortion === void 0) { compensateDistortion = true; }
  80174. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  80175. var _this = _super.call(this, name, position, scene) || this;
  80176. vrCameraMetrics.compensateDistortion = compensateDistortion;
  80177. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  80178. return _this;
  80179. }
  80180. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  80181. return "VRDeviceOrientationFreeCamera";
  80182. };
  80183. return VRDeviceOrientationFreeCamera;
  80184. }(BABYLON.DeviceOrientationCamera));
  80185. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  80186. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  80187. __extends(VRDeviceOrientationGamepadCamera, _super);
  80188. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  80189. if (compensateDistortion === void 0) { compensateDistortion = true; }
  80190. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  80191. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  80192. _this.inputs.addGamepad();
  80193. return _this;
  80194. }
  80195. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  80196. return "VRDeviceOrientationGamepadCamera";
  80197. };
  80198. return VRDeviceOrientationGamepadCamera;
  80199. }(VRDeviceOrientationFreeCamera));
  80200. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  80201. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  80202. __extends(VRDeviceOrientationArcRotateCamera, _super);
  80203. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  80204. if (compensateDistortion === void 0) { compensateDistortion = true; }
  80205. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  80206. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  80207. vrCameraMetrics.compensateDistortion = compensateDistortion;
  80208. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  80209. _this.inputs.addVRDeviceOrientation();
  80210. return _this;
  80211. }
  80212. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  80213. return "VRDeviceOrientationArcRotateCamera";
  80214. };
  80215. return VRDeviceOrientationArcRotateCamera;
  80216. }(BABYLON.ArcRotateCamera));
  80217. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  80218. })(BABYLON || (BABYLON = {}));
  80219. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  80220. var BABYLON;
  80221. (function (BABYLON) {
  80222. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  80223. __extends(AnaglyphFreeCamera, _super);
  80224. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  80225. var _this = _super.call(this, name, position, scene) || this;
  80226. _this.interaxialDistance = interaxialDistance;
  80227. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80228. return _this;
  80229. }
  80230. AnaglyphFreeCamera.prototype.getClassName = function () {
  80231. return "AnaglyphFreeCamera";
  80232. };
  80233. return AnaglyphFreeCamera;
  80234. }(BABYLON.FreeCamera));
  80235. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  80236. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  80237. __extends(AnaglyphArcRotateCamera, _super);
  80238. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  80239. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  80240. _this.interaxialDistance = interaxialDistance;
  80241. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80242. return _this;
  80243. }
  80244. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  80245. return "AnaglyphArcRotateCamera";
  80246. };
  80247. return AnaglyphArcRotateCamera;
  80248. }(BABYLON.ArcRotateCamera));
  80249. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  80250. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  80251. __extends(AnaglyphGamepadCamera, _super);
  80252. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  80253. var _this = _super.call(this, name, position, scene) || this;
  80254. _this.interaxialDistance = interaxialDistance;
  80255. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80256. return _this;
  80257. }
  80258. AnaglyphGamepadCamera.prototype.getClassName = function () {
  80259. return "AnaglyphGamepadCamera";
  80260. };
  80261. return AnaglyphGamepadCamera;
  80262. }(BABYLON.GamepadCamera));
  80263. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  80264. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  80265. __extends(AnaglyphUniversalCamera, _super);
  80266. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  80267. var _this = _super.call(this, name, position, scene) || this;
  80268. _this.interaxialDistance = interaxialDistance;
  80269. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80270. return _this;
  80271. }
  80272. AnaglyphUniversalCamera.prototype.getClassName = function () {
  80273. return "AnaglyphUniversalCamera";
  80274. };
  80275. return AnaglyphUniversalCamera;
  80276. }(BABYLON.UniversalCamera));
  80277. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  80278. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  80279. __extends(StereoscopicFreeCamera, _super);
  80280. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  80281. var _this = _super.call(this, name, position, scene) || this;
  80282. _this.interaxialDistance = interaxialDistance;
  80283. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80284. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80285. return _this;
  80286. }
  80287. StereoscopicFreeCamera.prototype.getClassName = function () {
  80288. return "StereoscopicFreeCamera";
  80289. };
  80290. return StereoscopicFreeCamera;
  80291. }(BABYLON.FreeCamera));
  80292. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  80293. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  80294. __extends(StereoscopicArcRotateCamera, _super);
  80295. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  80296. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  80297. _this.interaxialDistance = interaxialDistance;
  80298. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80299. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80300. return _this;
  80301. }
  80302. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  80303. return "StereoscopicArcRotateCamera";
  80304. };
  80305. return StereoscopicArcRotateCamera;
  80306. }(BABYLON.ArcRotateCamera));
  80307. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  80308. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  80309. __extends(StereoscopicGamepadCamera, _super);
  80310. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  80311. var _this = _super.call(this, name, position, scene) || this;
  80312. _this.interaxialDistance = interaxialDistance;
  80313. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80314. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80315. return _this;
  80316. }
  80317. StereoscopicGamepadCamera.prototype.getClassName = function () {
  80318. return "StereoscopicGamepadCamera";
  80319. };
  80320. return StereoscopicGamepadCamera;
  80321. }(BABYLON.GamepadCamera));
  80322. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  80323. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  80324. __extends(StereoscopicUniversalCamera, _super);
  80325. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  80326. var _this = _super.call(this, name, position, scene) || this;
  80327. _this.interaxialDistance = interaxialDistance;
  80328. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80329. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80330. return _this;
  80331. }
  80332. StereoscopicUniversalCamera.prototype.getClassName = function () {
  80333. return "StereoscopicUniversalCamera";
  80334. };
  80335. return StereoscopicUniversalCamera;
  80336. }(BABYLON.UniversalCamera));
  80337. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  80338. })(BABYLON || (BABYLON = {}));
  80339. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  80340. var BABYLON;
  80341. (function (BABYLON) {
  80342. var VRExperienceHelperGazer = /** @class */ (function () {
  80343. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  80344. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  80345. this.scene = scene;
  80346. this._pointerDownOnMeshAsked = false;
  80347. this._isActionableMesh = false;
  80348. this._teleportationRequestInitiated = false;
  80349. this._teleportationBackRequestInitiated = false;
  80350. this._dpadPressed = true;
  80351. this._activePointer = false;
  80352. this._id = VRExperienceHelperGazer._idCounter++;
  80353. // Gaze tracker
  80354. if (!gazeTrackerToClone) {
  80355. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  80356. this._gazeTracker.bakeCurrentTransformIntoVertices();
  80357. this._gazeTracker.isPickable = false;
  80358. this._gazeTracker.isVisible = false;
  80359. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  80360. targetMat.specularColor = BABYLON.Color3.Black();
  80361. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  80362. targetMat.backFaceCulling = false;
  80363. this._gazeTracker.material = targetMat;
  80364. }
  80365. else {
  80366. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  80367. }
  80368. }
  80369. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  80370. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  80371. };
  80372. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  80373. this._pointerDownOnMeshAsked = true;
  80374. if (this._currentMeshSelected && this._currentHit) {
  80375. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  80376. }
  80377. };
  80378. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  80379. if (this._currentMeshSelected && this._currentHit) {
  80380. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  80381. }
  80382. this._pointerDownOnMeshAsked = false;
  80383. };
  80384. VRExperienceHelperGazer.prototype._activatePointer = function () {
  80385. this._activePointer = true;
  80386. };
  80387. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  80388. this._activePointer = false;
  80389. };
  80390. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  80391. };
  80392. VRExperienceHelperGazer.prototype.dispose = function () {
  80393. this._interactionsEnabled = false;
  80394. this._teleportationEnabled = false;
  80395. };
  80396. VRExperienceHelperGazer._idCounter = 0;
  80397. return VRExperienceHelperGazer;
  80398. }());
  80399. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  80400. __extends(VRExperienceHelperControllerGazer, _super);
  80401. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  80402. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  80403. _this.webVRController = webVRController;
  80404. // Laser pointer
  80405. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  80406. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  80407. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  80408. laserPointerMaterial.alpha = 0.6;
  80409. _this._laserPointer.material = laserPointerMaterial;
  80410. _this._laserPointer.rotation.x = Math.PI / 2;
  80411. _this._laserPointer.position.z = -0.5;
  80412. _this._laserPointer.isVisible = false;
  80413. _this._laserPointer.parent = webVRController.mesh;
  80414. return _this;
  80415. }
  80416. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  80417. return this.webVRController.getForwardRay(length);
  80418. };
  80419. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  80420. _super.prototype._activatePointer.call(this);
  80421. this._laserPointer.isVisible = true;
  80422. };
  80423. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  80424. _super.prototype._deactivatePointer.call(this);
  80425. this._laserPointer.isVisible = false;
  80426. };
  80427. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  80428. this._laserPointer.material.emissiveColor = color;
  80429. };
  80430. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  80431. this._laserPointer.parent = mesh;
  80432. };
  80433. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  80434. this._laserPointer.scaling.y = distance;
  80435. this._laserPointer.position.z = -distance / 2;
  80436. };
  80437. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  80438. _super.prototype.dispose.call(this);
  80439. this._laserPointer.dispose();
  80440. };
  80441. return VRExperienceHelperControllerGazer;
  80442. }(VRExperienceHelperGazer));
  80443. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  80444. __extends(VRExperienceHelperCameraGazer, _super);
  80445. function VRExperienceHelperCameraGazer(getCamera, scene) {
  80446. var _this = _super.call(this, scene) || this;
  80447. _this.getCamera = getCamera;
  80448. return _this;
  80449. }
  80450. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  80451. var camera = this.getCamera();
  80452. if (camera) {
  80453. return camera.getForwardRay(length);
  80454. }
  80455. else {
  80456. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  80457. }
  80458. };
  80459. return VRExperienceHelperCameraGazer;
  80460. }(VRExperienceHelperGazer));
  80461. /**
  80462. * Helps to quickly add VR support to an existing scene.
  80463. * See http://doc.babylonjs.com/how_to/webvr_helper
  80464. */
  80465. var VRExperienceHelper = /** @class */ (function () {
  80466. /**
  80467. * Instantiates a VRExperienceHelper.
  80468. * Helps to quickly add VR support to an existing scene.
  80469. * @param scene The scene the VRExperienceHelper belongs to.
  80470. * @param webVROptions Options to modify the vr experience helper's behavior.
  80471. */
  80472. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  80473. if (webVROptions === void 0) { webVROptions = {}; }
  80474. var _this = this;
  80475. this.webVROptions = webVROptions;
  80476. // Can the system support WebVR, even if a headset isn't plugged in?
  80477. this._webVRsupported = false;
  80478. // If WebVR is supported, is a headset plugged in and are we ready to present?
  80479. this._webVRready = false;
  80480. // Are we waiting for the requestPresent callback to complete?
  80481. this._webVRrequesting = false;
  80482. // Are we presenting to the headset right now?
  80483. this._webVRpresenting = false;
  80484. // Are we presenting in the fullscreen fallback?
  80485. this._fullscreenVRpresenting = false;
  80486. /**
  80487. * Observable raised when entering VR.
  80488. */
  80489. this.onEnteringVRObservable = new BABYLON.Observable();
  80490. /**
  80491. * Observable raised when exiting VR.
  80492. */
  80493. this.onExitingVRObservable = new BABYLON.Observable();
  80494. /**
  80495. * Observable raised when controller mesh is loaded.
  80496. */
  80497. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  80498. this._useCustomVRButton = false;
  80499. this._teleportationRequested = false;
  80500. this._teleportActive = false;
  80501. this._floorMeshesCollection = [];
  80502. this._rotationAllowed = true;
  80503. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  80504. this._rotationRightAsked = false;
  80505. this._rotationLeftAsked = false;
  80506. this._isDefaultTeleportationTarget = true;
  80507. this._teleportationFillColor = "#444444";
  80508. this._teleportationBorderColor = "#FFFFFF";
  80509. this._rotationAngle = 0;
  80510. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  80511. this._padSensibilityUp = 0.65;
  80512. this._padSensibilityDown = 0.35;
  80513. this.leftController = null;
  80514. this.rightController = null;
  80515. /**
  80516. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  80517. */
  80518. this.onNewMeshSelected = new BABYLON.Observable();
  80519. /**
  80520. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  80521. */
  80522. this.onNewMeshPicked = new BABYLON.Observable();
  80523. /**
  80524. * Observable raised before camera teleportation
  80525. */
  80526. this.onBeforeCameraTeleport = new BABYLON.Observable();
  80527. /**
  80528. * Observable raised after camera teleportation
  80529. */
  80530. this.onAfterCameraTeleport = new BABYLON.Observable();
  80531. /**
  80532. * Observable raised when current selected mesh gets unselected
  80533. */
  80534. this.onSelectedMeshUnselected = new BABYLON.Observable();
  80535. /**
  80536. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  80537. */
  80538. this.teleportationEnabled = true;
  80539. this._teleportationInitialized = false;
  80540. this._interactionsEnabled = false;
  80541. this._interactionsRequested = false;
  80542. this._displayGaze = true;
  80543. this._displayLaserPointer = true;
  80544. this._onResize = function () {
  80545. _this.moveButtonToBottomRight();
  80546. if (_this._fullscreenVRpresenting && _this._webVRready) {
  80547. _this.exitVR();
  80548. }
  80549. };
  80550. this._onFullscreenChange = function () {
  80551. if (document.fullscreen !== undefined) {
  80552. _this._fullscreenVRpresenting = document.fullscreen;
  80553. }
  80554. else if (document.mozFullScreen !== undefined) {
  80555. _this._fullscreenVRpresenting = document.mozFullScreen;
  80556. }
  80557. else if (document.webkitIsFullScreen !== undefined) {
  80558. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  80559. }
  80560. else if (document.msIsFullScreen !== undefined) {
  80561. _this._fullscreenVRpresenting = document.msIsFullScreen;
  80562. }
  80563. if (!_this._fullscreenVRpresenting && _this._canvas) {
  80564. _this.exitVR();
  80565. if (!_this._useCustomVRButton) {
  80566. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  80567. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  80568. }
  80569. }
  80570. };
  80571. this.beforeRender = function () {
  80572. if (_this.leftController && _this.leftController._activePointer) {
  80573. _this._castRayAndSelectObject(_this.leftController);
  80574. }
  80575. if (_this.rightController && _this.rightController._activePointer) {
  80576. _this._castRayAndSelectObject(_this.rightController);
  80577. }
  80578. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  80579. _this._castRayAndSelectObject(_this._cameraGazer);
  80580. }
  80581. else {
  80582. _this._cameraGazer._gazeTracker.isVisible = false;
  80583. }
  80584. };
  80585. this._onNewGamepadConnected = function (gamepad) {
  80586. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  80587. if (gamepad.leftStick) {
  80588. gamepad.onleftstickchanged(function (stickValues) {
  80589. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  80590. // Listening to classic/xbox gamepad only if no VR controller is active
  80591. if ((!_this.leftController && !_this.rightController) ||
  80592. ((_this.leftController && !_this.leftController._activePointer) &&
  80593. (_this.rightController && !_this.rightController._activePointer))) {
  80594. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  80595. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  80596. }
  80597. }
  80598. });
  80599. }
  80600. if (gamepad.rightStick) {
  80601. gamepad.onrightstickchanged(function (stickValues) {
  80602. if (_this._teleportationInitialized) {
  80603. _this._checkRotate(stickValues, _this._cameraGazer);
  80604. }
  80605. });
  80606. }
  80607. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  80608. gamepad.onbuttondown(function (buttonPressed) {
  80609. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  80610. _this._cameraGazer._selectionPointerDown();
  80611. }
  80612. });
  80613. gamepad.onbuttonup(function (buttonPressed) {
  80614. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  80615. _this._cameraGazer._selectionPointerUp();
  80616. }
  80617. });
  80618. }
  80619. }
  80620. else {
  80621. var webVRController = gamepad;
  80622. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  80623. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  80624. _this.rightController = controller;
  80625. }
  80626. else {
  80627. _this.leftController = controller;
  80628. }
  80629. _this._tryEnableInteractionOnController(controller);
  80630. }
  80631. };
  80632. // 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
  80633. this._tryEnableInteractionOnController = function (controller) {
  80634. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  80635. _this._enableInteractionOnController(controller);
  80636. }
  80637. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  80638. _this._enableTeleportationOnController(controller);
  80639. }
  80640. };
  80641. this._onNewGamepadDisconnected = function (gamepad) {
  80642. if (gamepad instanceof BABYLON.WebVRController) {
  80643. if (gamepad.hand === "left" && _this.leftController != null) {
  80644. _this.leftController.dispose();
  80645. _this.leftController = null;
  80646. }
  80647. if (gamepad.hand === "right" && _this.rightController != null) {
  80648. _this.rightController.dispose();
  80649. _this.rightController = null;
  80650. }
  80651. }
  80652. };
  80653. this._workingVector = BABYLON.Vector3.Zero();
  80654. this._workingQuaternion = BABYLON.Quaternion.Identity();
  80655. this._workingMatrix = BABYLON.Matrix.Identity();
  80656. this._scene = scene;
  80657. this._canvas = scene.getEngine().getRenderingCanvas();
  80658. // Parse options
  80659. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  80660. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  80661. }
  80662. if (webVROptions.createDeviceOrientationCamera === undefined) {
  80663. webVROptions.createDeviceOrientationCamera = true;
  80664. }
  80665. if (webVROptions.defaultHeight === undefined) {
  80666. webVROptions.defaultHeight = 1.7;
  80667. }
  80668. if (webVROptions.useCustomVRButton) {
  80669. this._useCustomVRButton = true;
  80670. if (webVROptions.customVRButton) {
  80671. this._btnVR = webVROptions.customVRButton;
  80672. }
  80673. }
  80674. if (webVROptions.rayLength) {
  80675. this._rayLength = webVROptions.rayLength;
  80676. }
  80677. this._defaultHeight = webVROptions.defaultHeight;
  80678. // Set position
  80679. if (this._scene.activeCamera) {
  80680. this._position = this._scene.activeCamera.position.clone();
  80681. }
  80682. else {
  80683. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  80684. }
  80685. // Set non-vr camera
  80686. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  80687. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  80688. // Copy data from existing camera
  80689. if (this._scene.activeCamera) {
  80690. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  80691. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  80692. // Set rotation from previous camera
  80693. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  80694. var targetCamera = this._scene.activeCamera;
  80695. if (targetCamera.rotationQuaternion) {
  80696. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  80697. }
  80698. else {
  80699. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  80700. }
  80701. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  80702. }
  80703. }
  80704. this._scene.activeCamera = this._deviceOrientationCamera;
  80705. if (this._canvas) {
  80706. this._scene.activeCamera.attachControl(this._canvas);
  80707. }
  80708. }
  80709. else {
  80710. this._existingCamera = this._scene.activeCamera;
  80711. }
  80712. // Create VR cameras
  80713. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  80714. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  80715. }
  80716. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  80717. this._webVRCamera.useStandingMatrix();
  80718. // Create default button
  80719. if (!this._useCustomVRButton) {
  80720. this._btnVR = document.createElement("BUTTON");
  80721. this._btnVR.className = "babylonVRicon";
  80722. this._btnVR.id = "babylonVRiconbtn";
  80723. this._btnVR.title = "Click to switch to VR";
  80724. 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) }";
  80725. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  80726. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  80727. // css += ".babylonVRicon.vrdisplaysupported { }";
  80728. // css += ".babylonVRicon.vrdisplayready { }";
  80729. // css += ".babylonVRicon.vrdisplayrequesting { }";
  80730. var style = document.createElement('style');
  80731. style.appendChild(document.createTextNode(css));
  80732. document.getElementsByTagName('head')[0].appendChild(style);
  80733. this.moveButtonToBottomRight();
  80734. }
  80735. // VR button click event
  80736. if (this._btnVR) {
  80737. this._btnVR.addEventListener("click", function () {
  80738. if (!_this.isInVRMode) {
  80739. _this.enterVR();
  80740. }
  80741. else {
  80742. _this.exitVR();
  80743. }
  80744. });
  80745. }
  80746. // Window events
  80747. window.addEventListener("resize", this._onResize);
  80748. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  80749. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  80750. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  80751. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  80752. // Display vr button when headset is connected
  80753. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  80754. this.displayVRButton();
  80755. }
  80756. else {
  80757. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  80758. if (e.vrDisplay) {
  80759. _this.displayVRButton();
  80760. }
  80761. });
  80762. }
  80763. // Exiting VR mode using 'ESC' key on desktop
  80764. this._onKeyDown = function (event) {
  80765. if (event.keyCode === 27 && _this.isInVRMode) {
  80766. _this.exitVR();
  80767. }
  80768. };
  80769. document.addEventListener("keydown", this._onKeyDown);
  80770. // Exiting VR mode double tapping the touch screen
  80771. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  80772. if (_this.isInVRMode) {
  80773. _this.exitVR();
  80774. if (_this._fullscreenVRpresenting) {
  80775. _this._scene.getEngine().switchFullscreen(true);
  80776. }
  80777. }
  80778. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  80779. // Listen for WebVR display changes
  80780. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  80781. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  80782. this._onVRRequestPresentStart = function () {
  80783. _this._webVRrequesting = true;
  80784. _this.updateButtonVisibility();
  80785. };
  80786. this._onVRRequestPresentComplete = function (success) {
  80787. _this._webVRrequesting = false;
  80788. _this.updateButtonVisibility();
  80789. };
  80790. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  80791. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  80792. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  80793. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  80794. scene.onDisposeObservable.add(function () {
  80795. _this.dispose();
  80796. });
  80797. // Gamepad connection events
  80798. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  80799. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  80800. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  80801. this.updateButtonVisibility();
  80802. //create easing functions
  80803. this._circleEase = new BABYLON.CircleEase();
  80804. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  80805. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  80806. }
  80807. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  80808. /** Return this.onEnteringVRObservable
  80809. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  80810. */
  80811. get: function () {
  80812. return this.onEnteringVRObservable;
  80813. },
  80814. enumerable: true,
  80815. configurable: true
  80816. });
  80817. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  80818. /** Return this.onExitingVRObservable
  80819. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  80820. */
  80821. get: function () {
  80822. return this.onExitingVRObservable;
  80823. },
  80824. enumerable: true,
  80825. configurable: true
  80826. });
  80827. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  80828. /** Return this.onControllerMeshLoadedObservable
  80829. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  80830. */
  80831. get: function () {
  80832. return this.onControllerMeshLoadedObservable;
  80833. },
  80834. enumerable: true,
  80835. configurable: true
  80836. });
  80837. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  80838. /**
  80839. * The mesh used to display where the user is going to teleport.
  80840. */
  80841. get: function () {
  80842. return this._teleportationTarget;
  80843. },
  80844. /**
  80845. * Sets the mesh to be used to display where the user is going to teleport.
  80846. */
  80847. set: function (value) {
  80848. if (value) {
  80849. value.name = "teleportationTarget";
  80850. this._isDefaultTeleportationTarget = false;
  80851. this._teleportationTarget = value;
  80852. }
  80853. },
  80854. enumerable: true,
  80855. configurable: true
  80856. });
  80857. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  80858. /**
  80859. * The mesh used to display where the user is selecting,
  80860. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  80861. * See http://doc.babylonjs.com/resources/baking_transformations
  80862. */
  80863. get: function () {
  80864. return this._cameraGazer._gazeTracker;
  80865. },
  80866. set: function (value) {
  80867. if (value) {
  80868. this._cameraGazer._gazeTracker = value;
  80869. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  80870. this._cameraGazer._gazeTracker.isPickable = false;
  80871. this._cameraGazer._gazeTracker.isVisible = false;
  80872. this._cameraGazer._gazeTracker.name = "gazeTracker";
  80873. if (this.leftController) {
  80874. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  80875. }
  80876. if (this.rightController) {
  80877. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  80878. }
  80879. }
  80880. },
  80881. enumerable: true,
  80882. configurable: true
  80883. });
  80884. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  80885. /**
  80886. * If the ray of the gaze should be displayed.
  80887. */
  80888. get: function () {
  80889. return this._displayGaze;
  80890. },
  80891. /**
  80892. * Sets if the ray of the gaze should be displayed.
  80893. */
  80894. set: function (value) {
  80895. this._displayGaze = value;
  80896. if (!value) {
  80897. this._cameraGazer._gazeTracker.isVisible = false;
  80898. if (this.leftController) {
  80899. this.leftController._gazeTracker.isVisible = false;
  80900. }
  80901. if (this.rightController) {
  80902. this.rightController._gazeTracker.isVisible = false;
  80903. }
  80904. }
  80905. },
  80906. enumerable: true,
  80907. configurable: true
  80908. });
  80909. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  80910. /**
  80911. * If the ray of the LaserPointer should be displayed.
  80912. */
  80913. get: function () {
  80914. return this._displayLaserPointer;
  80915. },
  80916. /**
  80917. * Sets if the ray of the LaserPointer should be displayed.
  80918. */
  80919. set: function (value) {
  80920. this._displayLaserPointer = value;
  80921. if (!value) {
  80922. if (this.rightController) {
  80923. this.rightController._deactivatePointer();
  80924. this.rightController._gazeTracker.isVisible = false;
  80925. }
  80926. if (this.leftController) {
  80927. this.leftController._deactivatePointer();
  80928. this.leftController._gazeTracker.isVisible = false;
  80929. }
  80930. }
  80931. else {
  80932. if (this.rightController) {
  80933. this.rightController._activatePointer();
  80934. }
  80935. else if (this.leftController) {
  80936. this.leftController._activatePointer();
  80937. }
  80938. }
  80939. },
  80940. enumerable: true,
  80941. configurable: true
  80942. });
  80943. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  80944. /**
  80945. * The deviceOrientationCamera used as the camera when not in VR.
  80946. */
  80947. get: function () {
  80948. return this._deviceOrientationCamera;
  80949. },
  80950. enumerable: true,
  80951. configurable: true
  80952. });
  80953. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  80954. /**
  80955. * Based on the current WebVR support, returns the current VR camera used.
  80956. */
  80957. get: function () {
  80958. if (this._webVRready) {
  80959. return this._webVRCamera;
  80960. }
  80961. else {
  80962. return this._scene.activeCamera;
  80963. }
  80964. },
  80965. enumerable: true,
  80966. configurable: true
  80967. });
  80968. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  80969. /**
  80970. * The webVRCamera which is used when in VR.
  80971. */
  80972. get: function () {
  80973. return this._webVRCamera;
  80974. },
  80975. enumerable: true,
  80976. configurable: true
  80977. });
  80978. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  80979. /**
  80980. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  80981. */
  80982. get: function () {
  80983. return this._vrDeviceOrientationCamera;
  80984. },
  80985. enumerable: true,
  80986. configurable: true
  80987. });
  80988. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  80989. get: function () {
  80990. var result = this._cameraGazer._teleportationRequestInitiated
  80991. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  80992. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  80993. return result;
  80994. },
  80995. enumerable: true,
  80996. configurable: true
  80997. });
  80998. // Raised when one of the controller has loaded successfully its associated default mesh
  80999. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  81000. if (this.leftController && this.leftController.webVRController == webVRController) {
  81001. this._tryEnableInteractionOnController(this.leftController);
  81002. }
  81003. if (this.rightController && this.rightController.webVRController == webVRController) {
  81004. this._tryEnableInteractionOnController(this.rightController);
  81005. }
  81006. try {
  81007. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  81008. }
  81009. catch (err) {
  81010. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  81011. }
  81012. };
  81013. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  81014. /**
  81015. * Gets a value indicating if we are currently in VR mode.
  81016. */
  81017. get: function () {
  81018. return this._webVRpresenting || this._fullscreenVRpresenting;
  81019. },
  81020. enumerable: true,
  81021. configurable: true
  81022. });
  81023. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  81024. var vrDisplay = this._scene.getEngine().getVRDevice();
  81025. if (vrDisplay) {
  81026. var wasPresenting = this._webVRpresenting;
  81027. // A VR display is connected
  81028. this._webVRpresenting = vrDisplay.isPresenting;
  81029. if (wasPresenting && !this._webVRpresenting)
  81030. this.exitVR();
  81031. }
  81032. else {
  81033. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  81034. }
  81035. this.updateButtonVisibility();
  81036. };
  81037. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  81038. this._webVRsupported = eventArgs.vrSupported;
  81039. this._webVRready = !!eventArgs.vrDisplay;
  81040. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  81041. this.updateButtonVisibility();
  81042. };
  81043. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  81044. if (this._canvas && !this._useCustomVRButton) {
  81045. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  81046. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  81047. }
  81048. };
  81049. VRExperienceHelper.prototype.displayVRButton = function () {
  81050. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  81051. document.body.appendChild(this._btnVR);
  81052. this._btnVRDisplayed = true;
  81053. }
  81054. };
  81055. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  81056. if (!this._btnVR || this._useCustomVRButton) {
  81057. return;
  81058. }
  81059. this._btnVR.className = "babylonVRicon";
  81060. if (this.isInVRMode) {
  81061. this._btnVR.className += " vrdisplaypresenting";
  81062. }
  81063. else {
  81064. if (this._webVRready)
  81065. this._btnVR.className += " vrdisplayready";
  81066. if (this._webVRsupported)
  81067. this._btnVR.className += " vrdisplaysupported";
  81068. if (this._webVRrequesting)
  81069. this._btnVR.className += " vrdisplayrequesting";
  81070. }
  81071. };
  81072. /**
  81073. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  81074. * Otherwise, will use the fullscreen API.
  81075. */
  81076. VRExperienceHelper.prototype.enterVR = function () {
  81077. if (this.onEnteringVRObservable) {
  81078. try {
  81079. this.onEnteringVRObservable.notifyObservers(this);
  81080. }
  81081. catch (err) {
  81082. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  81083. }
  81084. }
  81085. if (this._scene.activeCamera) {
  81086. this._position = this._scene.activeCamera.position.clone();
  81087. // make sure that we return to the last active camera
  81088. this._existingCamera = this._scene.activeCamera;
  81089. }
  81090. if (this._webVRrequesting)
  81091. return;
  81092. // If WebVR is supported and a headset is connected
  81093. if (this._webVRready) {
  81094. if (!this._webVRpresenting) {
  81095. this._webVRCamera.position = this._position;
  81096. this._scene.activeCamera = this._webVRCamera;
  81097. }
  81098. }
  81099. else if (this._vrDeviceOrientationCamera) {
  81100. this._vrDeviceOrientationCamera.position = this._position;
  81101. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  81102. this._scene.getEngine().switchFullscreen(true);
  81103. this.updateButtonVisibility();
  81104. }
  81105. if (this._scene.activeCamera && this._canvas) {
  81106. this._scene.activeCamera.attachControl(this._canvas);
  81107. }
  81108. if (this._interactionsEnabled) {
  81109. this._scene.registerBeforeRender(this.beforeRender);
  81110. }
  81111. };
  81112. /**
  81113. * Attempt to exit VR, or fullscreen.
  81114. */
  81115. VRExperienceHelper.prototype.exitVR = function () {
  81116. if (this.onExitingVRObservable) {
  81117. try {
  81118. this.onExitingVRObservable.notifyObservers(this);
  81119. }
  81120. catch (err) {
  81121. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  81122. }
  81123. }
  81124. if (this._webVRpresenting) {
  81125. this._scene.getEngine().disableVR();
  81126. }
  81127. if (this._scene.activeCamera) {
  81128. this._position = this._scene.activeCamera.position.clone();
  81129. }
  81130. if (this._deviceOrientationCamera) {
  81131. this._deviceOrientationCamera.position = this._position;
  81132. this._scene.activeCamera = this._deviceOrientationCamera;
  81133. if (this._canvas) {
  81134. this._scene.activeCamera.attachControl(this._canvas);
  81135. }
  81136. }
  81137. else if (this._existingCamera) {
  81138. this._existingCamera.position = this._position;
  81139. this._scene.activeCamera = this._existingCamera;
  81140. }
  81141. this.updateButtonVisibility();
  81142. if (this._interactionsEnabled) {
  81143. this._scene.unregisterBeforeRender(this.beforeRender);
  81144. }
  81145. };
  81146. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  81147. /**
  81148. * The position of the vr experience helper.
  81149. */
  81150. get: function () {
  81151. return this._position;
  81152. },
  81153. /**
  81154. * Sets the position of the vr experience helper.
  81155. */
  81156. set: function (value) {
  81157. this._position = value;
  81158. if (this._scene.activeCamera) {
  81159. this._scene.activeCamera.position = value;
  81160. }
  81161. },
  81162. enumerable: true,
  81163. configurable: true
  81164. });
  81165. /**
  81166. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  81167. */
  81168. VRExperienceHelper.prototype.enableInteractions = function () {
  81169. var _this = this;
  81170. if (!this._interactionsEnabled) {
  81171. this._interactionsRequested = true;
  81172. if (this.leftController) {
  81173. this._enableInteractionOnController(this.leftController);
  81174. }
  81175. if (this.rightController) {
  81176. this._enableInteractionOnController(this.rightController);
  81177. }
  81178. this.raySelectionPredicate = function (mesh) {
  81179. return mesh.isVisible;
  81180. };
  81181. this.meshSelectionPredicate = function (mesh) {
  81182. return true;
  81183. };
  81184. this._raySelectionPredicate = function (mesh) {
  81185. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  81186. && mesh.name.indexOf("teleportationTarget") === -1
  81187. && mesh.name.indexOf("torusTeleportation") === -1
  81188. && mesh.name.indexOf("laserPointer") === -1)) {
  81189. return _this.raySelectionPredicate(mesh);
  81190. }
  81191. return false;
  81192. };
  81193. this._interactionsEnabled = true;
  81194. }
  81195. };
  81196. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  81197. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  81198. if (this._floorMeshesCollection[i].id === mesh.id) {
  81199. return true;
  81200. }
  81201. }
  81202. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  81203. return true;
  81204. }
  81205. return false;
  81206. };
  81207. /**
  81208. * Adds a floor mesh to be used for teleportation.
  81209. * @param floorMesh the mesh to be used for teleportation.
  81210. */
  81211. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  81212. if (!this._floorMeshesCollection) {
  81213. return;
  81214. }
  81215. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  81216. return;
  81217. }
  81218. this._floorMeshesCollection.push(floorMesh);
  81219. };
  81220. /**
  81221. * Removes a floor mesh from being used for teleportation.
  81222. * @param floorMesh the mesh to be removed.
  81223. */
  81224. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  81225. if (!this._floorMeshesCollection) {
  81226. return;
  81227. }
  81228. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  81229. if (meshIndex !== -1) {
  81230. this._floorMeshesCollection.splice(meshIndex, 1);
  81231. }
  81232. };
  81233. /**
  81234. * Enables interactions and teleportation using the VR controllers and gaze.
  81235. * @param vrTeleportationOptions options to modify teleportation behavior.
  81236. */
  81237. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  81238. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  81239. if (!this._teleportationInitialized) {
  81240. this._teleportationRequested = true;
  81241. this.enableInteractions();
  81242. if (vrTeleportationOptions.floorMeshName) {
  81243. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  81244. }
  81245. if (vrTeleportationOptions.floorMeshes) {
  81246. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  81247. }
  81248. if (this.leftController != null) {
  81249. this._enableTeleportationOnController(this.leftController);
  81250. }
  81251. if (this.rightController != null) {
  81252. this._enableTeleportationOnController(this.rightController);
  81253. }
  81254. // Creates an image processing post process for the vignette not relying
  81255. // on the main scene configuration for image processing to reduce setup and spaces
  81256. // (gamma/linear) conflicts.
  81257. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  81258. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  81259. imageProcessingConfiguration.vignetteEnabled = true;
  81260. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  81261. this._webVRCamera.detachPostProcess(this._postProcessMove);
  81262. this._teleportationInitialized = true;
  81263. if (this._isDefaultTeleportationTarget) {
  81264. this._createTeleportationCircles();
  81265. }
  81266. }
  81267. };
  81268. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  81269. var _this = this;
  81270. var controllerMesh = controller.webVRController.mesh;
  81271. if (controllerMesh) {
  81272. var makeNotPick = function (root) {
  81273. root.name += " laserPointer";
  81274. root.getChildMeshes().forEach(function (c) {
  81275. makeNotPick(c);
  81276. });
  81277. };
  81278. makeNotPick(controllerMesh);
  81279. var childMeshes = controllerMesh.getChildMeshes();
  81280. for (var i = 0; i < childMeshes.length; i++) {
  81281. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  81282. controllerMesh = childMeshes[i];
  81283. break;
  81284. }
  81285. }
  81286. controller._setLaserPointerParent(controllerMesh);
  81287. controller._interactionsEnabled = true;
  81288. controller._activatePointer();
  81289. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  81290. // Enabling / disabling laserPointer
  81291. if (_this._displayLaserPointer && stateObject.value === 1) {
  81292. if (controller._activePointer) {
  81293. controller._deactivatePointer();
  81294. }
  81295. else {
  81296. controller._activatePointer();
  81297. }
  81298. if (_this.displayGaze) {
  81299. controller._gazeTracker.isVisible = controller._activePointer;
  81300. }
  81301. }
  81302. });
  81303. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  81304. if (!controller._pointerDownOnMeshAsked) {
  81305. if (stateObject.value > _this._padSensibilityUp) {
  81306. controller._selectionPointerDown();
  81307. }
  81308. }
  81309. else if (stateObject.value < _this._padSensibilityDown) {
  81310. controller._selectionPointerUp();
  81311. }
  81312. });
  81313. }
  81314. };
  81315. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  81316. // Dont teleport if another gaze already requested teleportation
  81317. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  81318. return;
  81319. }
  81320. if (!gazer._teleportationRequestInitiated) {
  81321. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  81322. gazer._activatePointer();
  81323. gazer._teleportationRequestInitiated = true;
  81324. }
  81325. }
  81326. else {
  81327. // Listening to the proper controller values changes to confirm teleportation
  81328. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  81329. if (this._teleportActive) {
  81330. this._teleportCamera(this._haloCenter);
  81331. }
  81332. gazer._teleportationRequestInitiated = false;
  81333. }
  81334. }
  81335. };
  81336. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  81337. // Only rotate when user is not currently selecting a teleportation location
  81338. if (gazer._teleportationRequestInitiated) {
  81339. return;
  81340. }
  81341. if (!this._rotationLeftAsked) {
  81342. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  81343. this._rotationLeftAsked = true;
  81344. if (this._rotationAllowed) {
  81345. this._rotateCamera(false);
  81346. }
  81347. }
  81348. }
  81349. else {
  81350. if (stateObject.x > -this._padSensibilityDown) {
  81351. this._rotationLeftAsked = false;
  81352. }
  81353. }
  81354. if (!this._rotationRightAsked) {
  81355. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  81356. this._rotationRightAsked = true;
  81357. if (this._rotationAllowed) {
  81358. this._rotateCamera(true);
  81359. }
  81360. }
  81361. }
  81362. else {
  81363. if (stateObject.x < this._padSensibilityDown) {
  81364. this._rotationRightAsked = false;
  81365. }
  81366. }
  81367. };
  81368. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  81369. // Only teleport backwards when user is not currently selecting a teleportation location
  81370. if (gazer._teleportationRequestInitiated) {
  81371. return;
  81372. }
  81373. // Teleport backwards
  81374. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  81375. if (!gazer._teleportationBackRequestInitiated) {
  81376. if (!this.currentVRCamera) {
  81377. return;
  81378. }
  81379. // Get rotation and position of the current camera
  81380. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  81381. var position = this.currentVRCamera.position;
  81382. // If the camera has device position, use that instead
  81383. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  81384. rotation = this.currentVRCamera.deviceRotationQuaternion;
  81385. position = this.currentVRCamera.devicePosition;
  81386. }
  81387. // Get matrix with only the y rotation of the device rotation
  81388. rotation.toEulerAnglesToRef(this._workingVector);
  81389. this._workingVector.z = 0;
  81390. this._workingVector.x = 0;
  81391. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  81392. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  81393. // Rotate backwards ray by device rotation to cast at the ground behind the user
  81394. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  81395. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  81396. var ray = new BABYLON.Ray(position, this._workingVector);
  81397. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  81398. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  81399. this._teleportCamera(hit.pickedPoint);
  81400. }
  81401. gazer._teleportationBackRequestInitiated = true;
  81402. }
  81403. }
  81404. else {
  81405. gazer._teleportationBackRequestInitiated = false;
  81406. }
  81407. };
  81408. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  81409. var _this = this;
  81410. var controllerMesh = controller.webVRController.mesh;
  81411. if (controllerMesh) {
  81412. if (!controller._interactionsEnabled) {
  81413. this._enableInteractionOnController(controller);
  81414. }
  81415. controller._interactionsEnabled = true;
  81416. controller._teleportationEnabled = true;
  81417. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  81418. controller._dpadPressed = false;
  81419. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  81420. controller._dpadPressed = stateObject.pressed;
  81421. if (!controller._dpadPressed) {
  81422. _this._rotationLeftAsked = false;
  81423. _this._rotationRightAsked = false;
  81424. controller._teleportationBackRequestInitiated = false;
  81425. }
  81426. });
  81427. }
  81428. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  81429. if (_this.teleportationEnabled) {
  81430. _this._checkTeleportBackwards(stateObject, controller);
  81431. _this._checkTeleportWithRay(stateObject, controller);
  81432. }
  81433. _this._checkRotate(stateObject, controller);
  81434. });
  81435. }
  81436. };
  81437. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  81438. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  81439. this._teleportationTarget.isPickable = false;
  81440. var length = 512;
  81441. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  81442. dynamicTexture.hasAlpha = true;
  81443. var context = dynamicTexture.getContext();
  81444. var centerX = length / 2;
  81445. var centerY = length / 2;
  81446. var radius = 200;
  81447. context.beginPath();
  81448. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  81449. context.fillStyle = this._teleportationFillColor;
  81450. context.fill();
  81451. context.lineWidth = 10;
  81452. context.strokeStyle = this._teleportationBorderColor;
  81453. context.stroke();
  81454. context.closePath();
  81455. dynamicTexture.update();
  81456. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  81457. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  81458. this._teleportationTarget.material = teleportationCircleMaterial;
  81459. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  81460. torus.isPickable = false;
  81461. torus.parent = this._teleportationTarget;
  81462. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  81463. var keys = [];
  81464. keys.push({
  81465. frame: 0,
  81466. value: 0
  81467. });
  81468. keys.push({
  81469. frame: 30,
  81470. value: 0.4
  81471. });
  81472. keys.push({
  81473. frame: 60,
  81474. value: 0
  81475. });
  81476. animationInnerCircle.setKeys(keys);
  81477. var easingFunction = new BABYLON.SineEase();
  81478. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  81479. animationInnerCircle.setEasingFunction(easingFunction);
  81480. torus.animations = [];
  81481. torus.animations.push(animationInnerCircle);
  81482. this._scene.beginAnimation(torus, 0, 60, true);
  81483. this._hideTeleportationTarget();
  81484. };
  81485. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  81486. this._teleportActive = true;
  81487. if (this._teleportationInitialized) {
  81488. this._teleportationTarget.isVisible = true;
  81489. if (this._isDefaultTeleportationTarget) {
  81490. this._teleportationTarget.getChildren()[0].isVisible = true;
  81491. }
  81492. }
  81493. };
  81494. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  81495. this._teleportActive = false;
  81496. if (this._teleportationInitialized) {
  81497. this._teleportationTarget.isVisible = false;
  81498. if (this._isDefaultTeleportationTarget) {
  81499. this._teleportationTarget.getChildren()[0].isVisible = false;
  81500. }
  81501. }
  81502. };
  81503. VRExperienceHelper.prototype._rotateCamera = function (right) {
  81504. var _this = this;
  81505. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81506. return;
  81507. }
  81508. if (right) {
  81509. this._rotationAngle++;
  81510. }
  81511. else {
  81512. this._rotationAngle--;
  81513. }
  81514. this.currentVRCamera.animations = [];
  81515. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  81516. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81517. var animationRotationKeys = [];
  81518. animationRotationKeys.push({
  81519. frame: 0,
  81520. value: this.currentVRCamera.rotationQuaternion
  81521. });
  81522. animationRotationKeys.push({
  81523. frame: 6,
  81524. value: target
  81525. });
  81526. animationRotation.setKeys(animationRotationKeys);
  81527. animationRotation.setEasingFunction(this._circleEase);
  81528. this.currentVRCamera.animations.push(animationRotation);
  81529. this._postProcessMove.animations = [];
  81530. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81531. var vignetteWeightKeys = [];
  81532. vignetteWeightKeys.push({
  81533. frame: 0,
  81534. value: 0
  81535. });
  81536. vignetteWeightKeys.push({
  81537. frame: 3,
  81538. value: 4
  81539. });
  81540. vignetteWeightKeys.push({
  81541. frame: 6,
  81542. value: 0
  81543. });
  81544. animationPP.setKeys(vignetteWeightKeys);
  81545. animationPP.setEasingFunction(this._circleEase);
  81546. this._postProcessMove.animations.push(animationPP);
  81547. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81548. var vignetteStretchKeys = [];
  81549. vignetteStretchKeys.push({
  81550. frame: 0,
  81551. value: 0
  81552. });
  81553. vignetteStretchKeys.push({
  81554. frame: 3,
  81555. value: 10
  81556. });
  81557. vignetteStretchKeys.push({
  81558. frame: 6,
  81559. value: 0
  81560. });
  81561. animationPP2.setKeys(vignetteStretchKeys);
  81562. animationPP2.setEasingFunction(this._circleEase);
  81563. this._postProcessMove.animations.push(animationPP2);
  81564. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  81565. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  81566. this._postProcessMove.samples = 4;
  81567. this._webVRCamera.attachPostProcess(this._postProcessMove);
  81568. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  81569. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  81570. });
  81571. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  81572. };
  81573. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  81574. if (hit.pickedPoint) {
  81575. if (gazer._teleportationRequestInitiated) {
  81576. this._displayTeleportationTarget();
  81577. this._haloCenter.copyFrom(hit.pickedPoint);
  81578. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  81579. }
  81580. var pickNormal = hit.getNormal(true, false);
  81581. if (pickNormal) {
  81582. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  81583. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  81584. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  81585. }
  81586. this._teleportationTarget.position.y += 0.1;
  81587. }
  81588. };
  81589. VRExperienceHelper.prototype._teleportCamera = function (location) {
  81590. var _this = this;
  81591. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81592. return;
  81593. }
  81594. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  81595. // offset of the headset from the anchor.
  81596. if (this.webVRCamera.leftCamera) {
  81597. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  81598. this._workingVector.subtractInPlace(this.webVRCamera.position);
  81599. location.subtractToRef(this._workingVector, this._workingVector);
  81600. }
  81601. else {
  81602. this._workingVector.copyFrom(location);
  81603. }
  81604. // Add height to account for user's height offset
  81605. if (this.isInVRMode) {
  81606. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  81607. }
  81608. else {
  81609. this._workingVector.y += this._defaultHeight;
  81610. }
  81611. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  81612. // Create animation from the camera's position to the new location
  81613. this.currentVRCamera.animations = [];
  81614. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81615. var animationCameraTeleportationKeys = [{
  81616. frame: 0,
  81617. value: this.currentVRCamera.position
  81618. },
  81619. {
  81620. frame: 11,
  81621. value: this._workingVector
  81622. }
  81623. ];
  81624. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  81625. animationCameraTeleportation.setEasingFunction(this._circleEase);
  81626. this.currentVRCamera.animations.push(animationCameraTeleportation);
  81627. this._postProcessMove.animations = [];
  81628. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81629. var vignetteWeightKeys = [];
  81630. vignetteWeightKeys.push({
  81631. frame: 0,
  81632. value: 0
  81633. });
  81634. vignetteWeightKeys.push({
  81635. frame: 5,
  81636. value: 8
  81637. });
  81638. vignetteWeightKeys.push({
  81639. frame: 11,
  81640. value: 0
  81641. });
  81642. animationPP.setKeys(vignetteWeightKeys);
  81643. this._postProcessMove.animations.push(animationPP);
  81644. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81645. var vignetteStretchKeys = [];
  81646. vignetteStretchKeys.push({
  81647. frame: 0,
  81648. value: 0
  81649. });
  81650. vignetteStretchKeys.push({
  81651. frame: 5,
  81652. value: 10
  81653. });
  81654. vignetteStretchKeys.push({
  81655. frame: 11,
  81656. value: 0
  81657. });
  81658. animationPP2.setKeys(vignetteStretchKeys);
  81659. this._postProcessMove.animations.push(animationPP2);
  81660. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  81661. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  81662. this._webVRCamera.attachPostProcess(this._postProcessMove);
  81663. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  81664. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  81665. });
  81666. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  81667. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  81668. });
  81669. this._hideTeleportationTarget();
  81670. };
  81671. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  81672. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81673. return;
  81674. }
  81675. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  81676. // Moving the gazeTracker on the mesh face targetted
  81677. if (hit && hit.pickedPoint) {
  81678. if (this._displayGaze) {
  81679. var multiplier = 1;
  81680. gazer._gazeTracker.isVisible = true;
  81681. if (gazer._isActionableMesh) {
  81682. multiplier = 3;
  81683. }
  81684. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  81685. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  81686. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  81687. var pickNormal = hit.getNormal();
  81688. // To avoid z-fighting
  81689. var deltaFighting = 0.002;
  81690. if (pickNormal) {
  81691. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  81692. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  81693. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  81694. }
  81695. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  81696. if (gazer._gazeTracker.position.x < 0) {
  81697. gazer._gazeTracker.position.x += deltaFighting;
  81698. }
  81699. else {
  81700. gazer._gazeTracker.position.x -= deltaFighting;
  81701. }
  81702. if (gazer._gazeTracker.position.y < 0) {
  81703. gazer._gazeTracker.position.y += deltaFighting;
  81704. }
  81705. else {
  81706. gazer._gazeTracker.position.y -= deltaFighting;
  81707. }
  81708. if (gazer._gazeTracker.position.z < 0) {
  81709. gazer._gazeTracker.position.z += deltaFighting;
  81710. }
  81711. else {
  81712. gazer._gazeTracker.position.z -= deltaFighting;
  81713. }
  81714. }
  81715. // Changing the size of the laser pointer based on the distance from the targetted point
  81716. gazer._updatePointerDistance(hit.distance);
  81717. }
  81718. else {
  81719. gazer._gazeTracker.isVisible = false;
  81720. }
  81721. if (hit && hit.pickedMesh) {
  81722. gazer._currentHit = hit;
  81723. if (gazer._pointerDownOnMeshAsked) {
  81724. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  81725. }
  81726. // The object selected is the floor, we're in a teleportation scenario
  81727. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  81728. // Moving the teleportation area to this targetted point
  81729. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  81730. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  81731. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  81732. }
  81733. gazer._currentMeshSelected = null;
  81734. if (gazer._teleportationRequestInitiated) {
  81735. this._moveTeleportationSelectorTo(hit, gazer);
  81736. }
  81737. return;
  81738. }
  81739. // If not, we're in a selection scenario
  81740. //this._teleportationAllowed = false;
  81741. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  81742. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  81743. this.onNewMeshPicked.notifyObservers(hit);
  81744. gazer._currentMeshSelected = hit.pickedMesh;
  81745. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  81746. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  81747. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  81748. gazer._isActionableMesh = true;
  81749. }
  81750. else {
  81751. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81752. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81753. gazer._isActionableMesh = false;
  81754. }
  81755. try {
  81756. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  81757. }
  81758. catch (err) {
  81759. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  81760. }
  81761. }
  81762. else {
  81763. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  81764. gazer._currentMeshSelected = null;
  81765. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81766. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81767. }
  81768. }
  81769. }
  81770. else {
  81771. gazer._currentHit = null;
  81772. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  81773. gazer._currentMeshSelected = null;
  81774. //this._teleportationAllowed = false;
  81775. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81776. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81777. }
  81778. };
  81779. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  81780. if (mesh) {
  81781. this.onSelectedMeshUnselected.notifyObservers(mesh);
  81782. }
  81783. };
  81784. /**
  81785. * Sets the color of the laser ray from the vr controllers.
  81786. * @param color new color for the ray.
  81787. */
  81788. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  81789. if (this.leftController) {
  81790. this.leftController._setLaserPointerColor(color);
  81791. }
  81792. if (this.rightController) {
  81793. this.rightController._setLaserPointerColor(color);
  81794. }
  81795. };
  81796. /**
  81797. * Sets the color of the ray from the vr headsets gaze.
  81798. * @param color new color for the ray.
  81799. */
  81800. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  81801. if (!this._cameraGazer._gazeTracker.material) {
  81802. return;
  81803. }
  81804. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  81805. if (this.leftController) {
  81806. this.leftController._gazeTracker.material.emissiveColor = color;
  81807. }
  81808. if (this.rightController) {
  81809. this.rightController._gazeTracker.material.emissiveColor = color;
  81810. }
  81811. };
  81812. /**
  81813. * Exits VR and disposes of the vr experience helper
  81814. */
  81815. VRExperienceHelper.prototype.dispose = function () {
  81816. if (this.isInVRMode) {
  81817. this.exitVR();
  81818. }
  81819. if (this._postProcessMove) {
  81820. this._postProcessMove.dispose();
  81821. }
  81822. if (this._webVRCamera) {
  81823. this._webVRCamera.dispose();
  81824. }
  81825. if (this._vrDeviceOrientationCamera) {
  81826. this._vrDeviceOrientationCamera.dispose();
  81827. }
  81828. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  81829. document.body.removeChild(this._btnVR);
  81830. }
  81831. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  81832. this._deviceOrientationCamera.dispose();
  81833. }
  81834. if (this._cameraGazer) {
  81835. this._cameraGazer.dispose();
  81836. }
  81837. if (this.leftController) {
  81838. this.leftController.dispose();
  81839. }
  81840. if (this.rightController) {
  81841. this.rightController.dispose();
  81842. }
  81843. if (this._teleportationTarget) {
  81844. this._teleportationTarget.dispose();
  81845. }
  81846. this._floorMeshesCollection = [];
  81847. document.removeEventListener("keydown", this._onKeyDown);
  81848. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  81849. window.removeEventListener("resize", this._onResize);
  81850. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  81851. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  81852. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  81853. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  81854. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  81855. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  81856. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  81857. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  81858. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  81859. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  81860. this._scene.unregisterBeforeRender(this.beforeRender);
  81861. };
  81862. /**
  81863. * Gets the name of the VRExperienceHelper class
  81864. * @returns "VRExperienceHelper"
  81865. */
  81866. VRExperienceHelper.prototype.getClassName = function () {
  81867. return "VRExperienceHelper";
  81868. };
  81869. return VRExperienceHelper;
  81870. }());
  81871. BABYLON.VRExperienceHelper = VRExperienceHelper;
  81872. })(BABYLON || (BABYLON = {}));
  81873. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  81874. // Mainly based on these 2 articles :
  81875. // 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
  81876. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  81877. var BABYLON;
  81878. (function (BABYLON) {
  81879. var JoystickAxis;
  81880. (function (JoystickAxis) {
  81881. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  81882. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  81883. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  81884. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  81885. var VirtualJoystick = /** @class */ (function () {
  81886. function VirtualJoystick(leftJoystick) {
  81887. var _this = this;
  81888. if (leftJoystick) {
  81889. this._leftJoystick = true;
  81890. }
  81891. else {
  81892. this._leftJoystick = false;
  81893. }
  81894. VirtualJoystick._globalJoystickIndex++;
  81895. // By default left & right arrow keys are moving the X
  81896. // and up & down keys are moving the Y
  81897. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  81898. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  81899. this.reverseLeftRight = false;
  81900. this.reverseUpDown = false;
  81901. // collections of pointers
  81902. this._touches = new BABYLON.StringDictionary();
  81903. this.deltaPosition = BABYLON.Vector3.Zero();
  81904. this._joystickSensibility = 25;
  81905. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  81906. this._onResize = function (evt) {
  81907. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  81908. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  81909. if (VirtualJoystick.vjCanvas) {
  81910. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  81911. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  81912. }
  81913. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  81914. };
  81915. // injecting a canvas element on top of the canvas 3D game
  81916. if (!VirtualJoystick.vjCanvas) {
  81917. window.addEventListener("resize", this._onResize, false);
  81918. VirtualJoystick.vjCanvas = document.createElement("canvas");
  81919. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  81920. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  81921. VirtualJoystick.vjCanvas.width = window.innerWidth;
  81922. VirtualJoystick.vjCanvas.height = window.innerHeight;
  81923. VirtualJoystick.vjCanvas.style.width = "100%";
  81924. VirtualJoystick.vjCanvas.style.height = "100%";
  81925. VirtualJoystick.vjCanvas.style.position = "absolute";
  81926. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  81927. VirtualJoystick.vjCanvas.style.top = "0px";
  81928. VirtualJoystick.vjCanvas.style.left = "0px";
  81929. VirtualJoystick.vjCanvas.style.zIndex = "5";
  81930. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  81931. // Support for jQuery PEP polyfill
  81932. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  81933. var context = VirtualJoystick.vjCanvas.getContext('2d');
  81934. if (!context) {
  81935. throw new Error("Unable to create canvas for virtual joystick");
  81936. }
  81937. VirtualJoystick.vjCanvasContext = context;
  81938. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  81939. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  81940. document.body.appendChild(VirtualJoystick.vjCanvas);
  81941. }
  81942. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  81943. this.pressed = false;
  81944. // default joystick color
  81945. this._joystickColor = "cyan";
  81946. this._joystickPointerID = -1;
  81947. // current joystick position
  81948. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  81949. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  81950. // origin joystick position
  81951. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  81952. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  81953. this._onPointerDownHandlerRef = function (evt) {
  81954. _this._onPointerDown(evt);
  81955. };
  81956. this._onPointerMoveHandlerRef = function (evt) {
  81957. _this._onPointerMove(evt);
  81958. };
  81959. this._onPointerUpHandlerRef = function (evt) {
  81960. _this._onPointerUp(evt);
  81961. };
  81962. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  81963. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  81964. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  81965. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  81966. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  81967. evt.preventDefault(); // Disables system menu
  81968. }, false);
  81969. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  81970. }
  81971. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  81972. this._joystickSensibility = newJoystickSensibility;
  81973. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  81974. };
  81975. VirtualJoystick.prototype._onPointerDown = function (e) {
  81976. var positionOnScreenCondition;
  81977. e.preventDefault();
  81978. if (this._leftJoystick === true) {
  81979. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  81980. }
  81981. else {
  81982. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  81983. }
  81984. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  81985. // First contact will be dedicated to the virtual joystick
  81986. this._joystickPointerID = e.pointerId;
  81987. this._joystickPointerStartPos.x = e.clientX;
  81988. this._joystickPointerStartPos.y = e.clientY;
  81989. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  81990. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  81991. this._deltaJoystickVector.x = 0;
  81992. this._deltaJoystickVector.y = 0;
  81993. this.pressed = true;
  81994. this._touches.add(e.pointerId.toString(), e);
  81995. }
  81996. else {
  81997. // You can only trigger the action buttons with a joystick declared
  81998. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  81999. this._action();
  82000. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  82001. }
  82002. }
  82003. };
  82004. VirtualJoystick.prototype._onPointerMove = function (e) {
  82005. // If the current pointer is the one associated to the joystick (first touch contact)
  82006. if (this._joystickPointerID == e.pointerId) {
  82007. this._joystickPointerPos.x = e.clientX;
  82008. this._joystickPointerPos.y = e.clientY;
  82009. this._deltaJoystickVector = this._joystickPointerPos.clone();
  82010. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  82011. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  82012. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  82013. switch (this._axisTargetedByLeftAndRight) {
  82014. case JoystickAxis.X:
  82015. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  82016. break;
  82017. case JoystickAxis.Y:
  82018. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  82019. break;
  82020. case JoystickAxis.Z:
  82021. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  82022. break;
  82023. }
  82024. var directionUpDown = this.reverseUpDown ? 1 : -1;
  82025. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  82026. switch (this._axisTargetedByUpAndDown) {
  82027. case JoystickAxis.X:
  82028. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  82029. break;
  82030. case JoystickAxis.Y:
  82031. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  82032. break;
  82033. case JoystickAxis.Z:
  82034. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  82035. break;
  82036. }
  82037. }
  82038. else {
  82039. var data = this._touches.get(e.pointerId.toString());
  82040. if (data) {
  82041. data.x = e.clientX;
  82042. data.y = e.clientY;
  82043. }
  82044. }
  82045. };
  82046. VirtualJoystick.prototype._onPointerUp = function (e) {
  82047. if (this._joystickPointerID == e.pointerId) {
  82048. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  82049. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  82050. this._joystickPointerID = -1;
  82051. this.pressed = false;
  82052. }
  82053. else {
  82054. var touch = this._touches.get(e.pointerId.toString());
  82055. if (touch) {
  82056. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  82057. }
  82058. }
  82059. this._deltaJoystickVector.x = 0;
  82060. this._deltaJoystickVector.y = 0;
  82061. this._touches.remove(e.pointerId.toString());
  82062. };
  82063. /**
  82064. * Change the color of the virtual joystick
  82065. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  82066. */
  82067. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  82068. this._joystickColor = newColor;
  82069. };
  82070. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  82071. this._action = action;
  82072. };
  82073. // Define which axis you'd like to control for left & right
  82074. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  82075. switch (axis) {
  82076. case JoystickAxis.X:
  82077. case JoystickAxis.Y:
  82078. case JoystickAxis.Z:
  82079. this._axisTargetedByLeftAndRight = axis;
  82080. break;
  82081. default:
  82082. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  82083. break;
  82084. }
  82085. };
  82086. // Define which axis you'd like to control for up & down
  82087. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  82088. switch (axis) {
  82089. case JoystickAxis.X:
  82090. case JoystickAxis.Y:
  82091. case JoystickAxis.Z:
  82092. this._axisTargetedByUpAndDown = axis;
  82093. break;
  82094. default:
  82095. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  82096. break;
  82097. }
  82098. };
  82099. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  82100. var _this = this;
  82101. if (this.pressed) {
  82102. this._touches.forEach(function (key, touch) {
  82103. if (touch.pointerId === _this._joystickPointerID) {
  82104. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  82105. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  82106. VirtualJoystick.vjCanvasContext.beginPath();
  82107. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  82108. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  82109. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  82110. VirtualJoystick.vjCanvasContext.stroke();
  82111. VirtualJoystick.vjCanvasContext.closePath();
  82112. VirtualJoystick.vjCanvasContext.beginPath();
  82113. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  82114. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  82115. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  82116. VirtualJoystick.vjCanvasContext.stroke();
  82117. VirtualJoystick.vjCanvasContext.closePath();
  82118. VirtualJoystick.vjCanvasContext.beginPath();
  82119. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  82120. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  82121. VirtualJoystick.vjCanvasContext.stroke();
  82122. VirtualJoystick.vjCanvasContext.closePath();
  82123. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  82124. }
  82125. else {
  82126. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  82127. VirtualJoystick.vjCanvasContext.beginPath();
  82128. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  82129. VirtualJoystick.vjCanvasContext.beginPath();
  82130. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  82131. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  82132. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  82133. VirtualJoystick.vjCanvasContext.stroke();
  82134. VirtualJoystick.vjCanvasContext.closePath();
  82135. touch.prevX = touch.x;
  82136. touch.prevY = touch.y;
  82137. }
  82138. ;
  82139. });
  82140. }
  82141. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  82142. };
  82143. VirtualJoystick.prototype.releaseCanvas = function () {
  82144. if (VirtualJoystick.vjCanvas) {
  82145. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  82146. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  82147. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  82148. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  82149. window.removeEventListener("resize", this._onResize);
  82150. document.body.removeChild(VirtualJoystick.vjCanvas);
  82151. VirtualJoystick.vjCanvas = null;
  82152. }
  82153. };
  82154. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  82155. VirtualJoystick._globalJoystickIndex = 0;
  82156. return VirtualJoystick;
  82157. }());
  82158. BABYLON.VirtualJoystick = VirtualJoystick;
  82159. })(BABYLON || (BABYLON = {}));
  82160. //# sourceMappingURL=babylon.virtualJoystick.js.map
  82161. var BABYLON;
  82162. (function (BABYLON) {
  82163. // We're mainly based on the logic defined into the FreeCamera code
  82164. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  82165. __extends(VirtualJoysticksCamera, _super);
  82166. function VirtualJoysticksCamera(name, position, scene) {
  82167. var _this = _super.call(this, name, position, scene) || this;
  82168. _this.inputs.addVirtualJoystick();
  82169. return _this;
  82170. }
  82171. VirtualJoysticksCamera.prototype.getClassName = function () {
  82172. return "VirtualJoysticksCamera";
  82173. };
  82174. return VirtualJoysticksCamera;
  82175. }(BABYLON.FreeCamera));
  82176. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  82177. })(BABYLON || (BABYLON = {}));
  82178. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  82179. var BABYLON;
  82180. (function (BABYLON) {
  82181. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  82182. function FreeCameraVirtualJoystickInput() {
  82183. }
  82184. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  82185. return this._leftjoystick;
  82186. };
  82187. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  82188. return this._rightjoystick;
  82189. };
  82190. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  82191. if (this._leftjoystick) {
  82192. var camera = this.camera;
  82193. var speed = camera._computeLocalCameraSpeed() * 50;
  82194. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  82195. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  82196. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  82197. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  82198. if (!this._leftjoystick.pressed) {
  82199. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  82200. }
  82201. if (!this._rightjoystick.pressed) {
  82202. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  82203. }
  82204. }
  82205. };
  82206. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  82207. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  82208. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  82209. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  82210. this._leftjoystick.setJoystickSensibility(0.15);
  82211. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  82212. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  82213. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  82214. this._rightjoystick.reverseUpDown = true;
  82215. this._rightjoystick.setJoystickSensibility(0.05);
  82216. this._rightjoystick.setJoystickColor("yellow");
  82217. };
  82218. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  82219. this._leftjoystick.releaseCanvas();
  82220. this._rightjoystick.releaseCanvas();
  82221. };
  82222. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  82223. return "FreeCameraVirtualJoystickInput";
  82224. };
  82225. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  82226. return "virtualJoystick";
  82227. };
  82228. return FreeCameraVirtualJoystickInput;
  82229. }());
  82230. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  82231. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  82232. })(BABYLON || (BABYLON = {}));
  82233. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  82234. var BABYLON;
  82235. (function (BABYLON) {
  82236. var SimplificationSettings = /** @class */ (function () {
  82237. function SimplificationSettings(quality, distance, optimizeMesh) {
  82238. this.quality = quality;
  82239. this.distance = distance;
  82240. this.optimizeMesh = optimizeMesh;
  82241. }
  82242. return SimplificationSettings;
  82243. }());
  82244. BABYLON.SimplificationSettings = SimplificationSettings;
  82245. var SimplificationQueue = /** @class */ (function () {
  82246. function SimplificationQueue() {
  82247. this.running = false;
  82248. this._simplificationArray = [];
  82249. }
  82250. SimplificationQueue.prototype.addTask = function (task) {
  82251. this._simplificationArray.push(task);
  82252. };
  82253. SimplificationQueue.prototype.executeNext = function () {
  82254. var task = this._simplificationArray.pop();
  82255. if (task) {
  82256. this.running = true;
  82257. this.runSimplification(task);
  82258. }
  82259. else {
  82260. this.running = false;
  82261. }
  82262. };
  82263. SimplificationQueue.prototype.runSimplification = function (task) {
  82264. var _this = this;
  82265. if (task.parallelProcessing) {
  82266. //parallel simplifier
  82267. task.settings.forEach(function (setting) {
  82268. var simplifier = _this.getSimplifier(task);
  82269. simplifier.simplify(setting, function (newMesh) {
  82270. task.mesh.addLODLevel(setting.distance, newMesh);
  82271. newMesh.isVisible = true;
  82272. //check if it is the last
  82273. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  82274. //all done, run the success callback.
  82275. task.successCallback();
  82276. }
  82277. _this.executeNext();
  82278. });
  82279. });
  82280. }
  82281. else {
  82282. //single simplifier.
  82283. var simplifier = this.getSimplifier(task);
  82284. var runDecimation = function (setting, callback) {
  82285. simplifier.simplify(setting, function (newMesh) {
  82286. task.mesh.addLODLevel(setting.distance, newMesh);
  82287. newMesh.isVisible = true;
  82288. //run the next quality level
  82289. callback();
  82290. });
  82291. };
  82292. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  82293. runDecimation(task.settings[loop.index], function () {
  82294. loop.executeNext();
  82295. });
  82296. }, function () {
  82297. //execution ended, run the success callback.
  82298. if (task.successCallback) {
  82299. task.successCallback();
  82300. }
  82301. _this.executeNext();
  82302. });
  82303. }
  82304. };
  82305. SimplificationQueue.prototype.getSimplifier = function (task) {
  82306. switch (task.simplificationType) {
  82307. case SimplificationType.QUADRATIC:
  82308. default:
  82309. return new QuadraticErrorSimplification(task.mesh);
  82310. }
  82311. };
  82312. return SimplificationQueue;
  82313. }());
  82314. BABYLON.SimplificationQueue = SimplificationQueue;
  82315. /**
  82316. * The implemented types of simplification.
  82317. * At the moment only Quadratic Error Decimation is implemented.
  82318. */
  82319. var SimplificationType;
  82320. (function (SimplificationType) {
  82321. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  82322. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  82323. var DecimationTriangle = /** @class */ (function () {
  82324. function DecimationTriangle(vertices) {
  82325. this.vertices = vertices;
  82326. this.error = new Array(4);
  82327. this.deleted = false;
  82328. this.isDirty = false;
  82329. this.deletePending = false;
  82330. this.borderFactor = 0;
  82331. }
  82332. return DecimationTriangle;
  82333. }());
  82334. BABYLON.DecimationTriangle = DecimationTriangle;
  82335. var DecimationVertex = /** @class */ (function () {
  82336. function DecimationVertex(position, id) {
  82337. this.position = position;
  82338. this.id = id;
  82339. this.isBorder = true;
  82340. this.q = new QuadraticMatrix();
  82341. this.triangleCount = 0;
  82342. this.triangleStart = 0;
  82343. this.originalOffsets = [];
  82344. }
  82345. DecimationVertex.prototype.updatePosition = function (newPosition) {
  82346. this.position.copyFrom(newPosition);
  82347. };
  82348. return DecimationVertex;
  82349. }());
  82350. BABYLON.DecimationVertex = DecimationVertex;
  82351. var QuadraticMatrix = /** @class */ (function () {
  82352. function QuadraticMatrix(data) {
  82353. this.data = new Array(10);
  82354. for (var i = 0; i < 10; ++i) {
  82355. if (data && data[i]) {
  82356. this.data[i] = data[i];
  82357. }
  82358. else {
  82359. this.data[i] = 0;
  82360. }
  82361. }
  82362. }
  82363. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  82364. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  82365. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  82366. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  82367. return det;
  82368. };
  82369. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  82370. for (var i = 0; i < 10; ++i) {
  82371. this.data[i] += matrix.data[i];
  82372. }
  82373. };
  82374. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  82375. for (var i = 0; i < 10; ++i) {
  82376. this.data[i] += data[i];
  82377. }
  82378. };
  82379. QuadraticMatrix.prototype.add = function (matrix) {
  82380. var m = new QuadraticMatrix();
  82381. for (var i = 0; i < 10; ++i) {
  82382. m.data[i] = this.data[i] + matrix.data[i];
  82383. }
  82384. return m;
  82385. };
  82386. QuadraticMatrix.FromData = function (a, b, c, d) {
  82387. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  82388. };
  82389. //returning an array to avoid garbage collection
  82390. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  82391. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  82392. };
  82393. return QuadraticMatrix;
  82394. }());
  82395. BABYLON.QuadraticMatrix = QuadraticMatrix;
  82396. var Reference = /** @class */ (function () {
  82397. function Reference(vertexId, triangleId) {
  82398. this.vertexId = vertexId;
  82399. this.triangleId = triangleId;
  82400. }
  82401. return Reference;
  82402. }());
  82403. BABYLON.Reference = Reference;
  82404. /**
  82405. * An implementation of the Quadratic Error simplification algorithm.
  82406. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  82407. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  82408. * @author RaananW
  82409. */
  82410. var QuadraticErrorSimplification = /** @class */ (function () {
  82411. function QuadraticErrorSimplification(_mesh) {
  82412. this._mesh = _mesh;
  82413. this.syncIterations = 5000;
  82414. this.aggressiveness = 7;
  82415. this.decimationIterations = 100;
  82416. this.boundingBoxEpsilon = BABYLON.Epsilon;
  82417. }
  82418. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  82419. var _this = this;
  82420. this.initDecimatedMesh();
  82421. //iterating through the submeshes array, one after the other.
  82422. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  82423. _this.initWithMesh(loop.index, function () {
  82424. _this.runDecimation(settings, loop.index, function () {
  82425. loop.executeNext();
  82426. });
  82427. }, settings.optimizeMesh);
  82428. }, function () {
  82429. setTimeout(function () {
  82430. successCallback(_this._reconstructedMesh);
  82431. }, 0);
  82432. });
  82433. };
  82434. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  82435. var _this = this;
  82436. var targetCount = ~~(this.triangles.length * settings.quality);
  82437. var deletedTriangles = 0;
  82438. var triangleCount = this.triangles.length;
  82439. var iterationFunction = function (iteration, callback) {
  82440. setTimeout(function () {
  82441. if (iteration % 5 === 0) {
  82442. _this.updateMesh(iteration === 0);
  82443. }
  82444. for (var i = 0; i < _this.triangles.length; ++i) {
  82445. _this.triangles[i].isDirty = false;
  82446. }
  82447. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  82448. var trianglesIterator = function (i) {
  82449. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  82450. var t = _this.triangles[tIdx];
  82451. if (!t)
  82452. return;
  82453. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  82454. return;
  82455. }
  82456. for (var j = 0; j < 3; ++j) {
  82457. if (t.error[j] < threshold) {
  82458. var deleted0 = [];
  82459. var deleted1 = [];
  82460. var v0 = t.vertices[j];
  82461. var v1 = t.vertices[(j + 1) % 3];
  82462. if (v0.isBorder || v1.isBorder)
  82463. continue;
  82464. var p = BABYLON.Vector3.Zero();
  82465. var n = BABYLON.Vector3.Zero();
  82466. var uv = BABYLON.Vector2.Zero();
  82467. var color = new BABYLON.Color4(0, 0, 0, 1);
  82468. _this.calculateError(v0, v1, p, n, uv, color);
  82469. var delTr = new Array();
  82470. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  82471. continue;
  82472. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  82473. continue;
  82474. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  82475. continue;
  82476. var uniqueArray = new Array();
  82477. delTr.forEach(function (deletedT) {
  82478. if (uniqueArray.indexOf(deletedT) === -1) {
  82479. deletedT.deletePending = true;
  82480. uniqueArray.push(deletedT);
  82481. }
  82482. });
  82483. if (uniqueArray.length % 2 !== 0) {
  82484. continue;
  82485. }
  82486. v0.q = v1.q.add(v0.q);
  82487. v0.updatePosition(p);
  82488. var tStart = _this.references.length;
  82489. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  82490. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  82491. var tCount = _this.references.length - tStart;
  82492. if (tCount <= v0.triangleCount) {
  82493. if (tCount) {
  82494. for (var c = 0; c < tCount; c++) {
  82495. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  82496. }
  82497. }
  82498. }
  82499. else {
  82500. v0.triangleStart = tStart;
  82501. }
  82502. v0.triangleCount = tCount;
  82503. break;
  82504. }
  82505. }
  82506. };
  82507. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  82508. }, 0);
  82509. };
  82510. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  82511. if (triangleCount - deletedTriangles <= targetCount)
  82512. loop.breakLoop();
  82513. else {
  82514. iterationFunction(loop.index, function () {
  82515. loop.executeNext();
  82516. });
  82517. }
  82518. }, function () {
  82519. setTimeout(function () {
  82520. //reconstruct this part of the mesh
  82521. _this.reconstructMesh(submeshIndex);
  82522. successCallback();
  82523. }, 0);
  82524. });
  82525. };
  82526. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  82527. var _this = this;
  82528. this.vertices = [];
  82529. this.triangles = [];
  82530. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  82531. var indices = this._mesh.getIndices();
  82532. var submesh = this._mesh.subMeshes[submeshIndex];
  82533. var findInVertices = function (positionToSearch) {
  82534. if (optimizeMesh) {
  82535. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  82536. if (_this.vertices[ii].position.equals(positionToSearch)) {
  82537. return _this.vertices[ii];
  82538. }
  82539. }
  82540. }
  82541. return null;
  82542. };
  82543. var vertexReferences = [];
  82544. var vertexInit = function (i) {
  82545. if (!positionData) {
  82546. return;
  82547. }
  82548. var offset = i + submesh.verticesStart;
  82549. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  82550. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  82551. vertex.originalOffsets.push(offset);
  82552. if (vertex.id === _this.vertices.length) {
  82553. _this.vertices.push(vertex);
  82554. }
  82555. vertexReferences.push(vertex.id);
  82556. };
  82557. //var totalVertices = mesh.getTotalVertices();
  82558. var totalVertices = submesh.verticesCount;
  82559. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  82560. var indicesInit = function (i) {
  82561. if (!indices) {
  82562. return;
  82563. }
  82564. var offset = (submesh.indexStart / 3) + i;
  82565. var pos = (offset * 3);
  82566. var i0 = indices[pos + 0];
  82567. var i1 = indices[pos + 1];
  82568. var i2 = indices[pos + 2];
  82569. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  82570. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  82571. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  82572. var triangle = new DecimationTriangle([v0, v1, v2]);
  82573. triangle.originalOffset = pos;
  82574. _this.triangles.push(triangle);
  82575. };
  82576. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  82577. _this.init(callback);
  82578. });
  82579. });
  82580. };
  82581. QuadraticErrorSimplification.prototype.init = function (callback) {
  82582. var _this = this;
  82583. var triangleInit1 = function (i) {
  82584. var t = _this.triangles[i];
  82585. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  82586. for (var j = 0; j < 3; j++) {
  82587. 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))));
  82588. }
  82589. };
  82590. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  82591. var triangleInit2 = function (i) {
  82592. var t = _this.triangles[i];
  82593. for (var j = 0; j < 3; ++j) {
  82594. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  82595. }
  82596. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  82597. };
  82598. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  82599. callback();
  82600. });
  82601. });
  82602. };
  82603. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  82604. var newTriangles = [];
  82605. var i;
  82606. for (i = 0; i < this.vertices.length; ++i) {
  82607. this.vertices[i].triangleCount = 0;
  82608. }
  82609. var t;
  82610. var j;
  82611. for (i = 0; i < this.triangles.length; ++i) {
  82612. if (!this.triangles[i].deleted) {
  82613. t = this.triangles[i];
  82614. for (j = 0; j < 3; ++j) {
  82615. t.vertices[j].triangleCount = 1;
  82616. }
  82617. newTriangles.push(t);
  82618. }
  82619. }
  82620. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  82621. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  82622. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  82623. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  82624. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  82625. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  82626. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  82627. var vertexCount = 0;
  82628. for (i = 0; i < this.vertices.length; ++i) {
  82629. var vertex = this.vertices[i];
  82630. vertex.id = vertexCount;
  82631. if (vertex.triangleCount) {
  82632. vertex.originalOffsets.forEach(function (originalOffset) {
  82633. if (!normalData) {
  82634. return;
  82635. }
  82636. newPositionData.push(vertex.position.x);
  82637. newPositionData.push(vertex.position.y);
  82638. newPositionData.push(vertex.position.z);
  82639. newNormalData.push(normalData[originalOffset * 3]);
  82640. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  82641. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  82642. if (uvs && uvs.length) {
  82643. newUVsData.push(uvs[(originalOffset * 2)]);
  82644. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  82645. }
  82646. else if (colorsData && colorsData.length) {
  82647. newColorsData.push(colorsData[(originalOffset * 4)]);
  82648. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  82649. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  82650. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  82651. }
  82652. ++vertexCount;
  82653. });
  82654. }
  82655. }
  82656. var startingIndex = this._reconstructedMesh.getTotalIndices();
  82657. var startingVertex = this._reconstructedMesh.getTotalVertices();
  82658. var submeshesArray = this._reconstructedMesh.subMeshes;
  82659. this._reconstructedMesh.subMeshes = [];
  82660. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  82661. var originalIndices = this._mesh.getIndices();
  82662. for (i = 0; i < newTriangles.length; ++i) {
  82663. t = newTriangles[i]; //now get the new referencing point for each vertex
  82664. [0, 1, 2].forEach(function (idx) {
  82665. var id = originalIndices[t.originalOffset + idx];
  82666. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  82667. if (offset < 0)
  82668. offset = 0;
  82669. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  82670. });
  82671. }
  82672. //overwriting the old vertex buffers and indices.
  82673. this._reconstructedMesh.setIndices(newIndicesArray);
  82674. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  82675. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  82676. if (newUVsData.length > 0)
  82677. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  82678. if (newColorsData.length > 0)
  82679. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  82680. //create submesh
  82681. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  82682. if (submeshIndex > 0) {
  82683. this._reconstructedMesh.subMeshes = [];
  82684. submeshesArray.forEach(function (submesh) {
  82685. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  82686. });
  82687. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  82688. }
  82689. };
  82690. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  82691. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  82692. this._reconstructedMesh.material = this._mesh.material;
  82693. this._reconstructedMesh.parent = this._mesh.parent;
  82694. this._reconstructedMesh.isVisible = false;
  82695. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  82696. };
  82697. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  82698. for (var i = 0; i < vertex1.triangleCount; ++i) {
  82699. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  82700. if (t.deleted)
  82701. continue;
  82702. var s = this.references[vertex1.triangleStart + i].vertexId;
  82703. var v1 = t.vertices[(s + 1) % 3];
  82704. var v2 = t.vertices[(s + 2) % 3];
  82705. if ((v1 === vertex2 || v2 === vertex2)) {
  82706. deletedArray[i] = true;
  82707. delTr.push(t);
  82708. continue;
  82709. }
  82710. var d1 = v1.position.subtract(point);
  82711. d1 = d1.normalize();
  82712. var d2 = v2.position.subtract(point);
  82713. d2 = d2.normalize();
  82714. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  82715. return true;
  82716. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  82717. deletedArray[i] = false;
  82718. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  82719. return true;
  82720. }
  82721. return false;
  82722. };
  82723. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  82724. var newDeleted = deletedTriangles;
  82725. for (var i = 0; i < vertex.triangleCount; ++i) {
  82726. var ref = this.references[vertex.triangleStart + i];
  82727. var t = this.triangles[ref.triangleId];
  82728. if (t.deleted)
  82729. continue;
  82730. if (deletedArray[i] && t.deletePending) {
  82731. t.deleted = true;
  82732. newDeleted++;
  82733. continue;
  82734. }
  82735. t.vertices[ref.vertexId] = origVertex;
  82736. t.isDirty = true;
  82737. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  82738. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  82739. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  82740. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  82741. this.references.push(ref);
  82742. }
  82743. return newDeleted;
  82744. };
  82745. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  82746. for (var i = 0; i < this.vertices.length; ++i) {
  82747. var vCount = [];
  82748. var vId = [];
  82749. var v = this.vertices[i];
  82750. var j;
  82751. for (j = 0; j < v.triangleCount; ++j) {
  82752. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  82753. for (var ii = 0; ii < 3; ii++) {
  82754. var ofs = 0;
  82755. var vv = triangle.vertices[ii];
  82756. while (ofs < vCount.length) {
  82757. if (vId[ofs] === vv.id)
  82758. break;
  82759. ++ofs;
  82760. }
  82761. if (ofs === vCount.length) {
  82762. vCount.push(1);
  82763. vId.push(vv.id);
  82764. }
  82765. else {
  82766. vCount[ofs]++;
  82767. }
  82768. }
  82769. }
  82770. for (j = 0; j < vCount.length; ++j) {
  82771. if (vCount[j] === 1) {
  82772. this.vertices[vId[j]].isBorder = true;
  82773. }
  82774. else {
  82775. this.vertices[vId[j]].isBorder = false;
  82776. }
  82777. }
  82778. }
  82779. };
  82780. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  82781. if (identifyBorders === void 0) { identifyBorders = false; }
  82782. var i;
  82783. if (!identifyBorders) {
  82784. var newTrianglesVector = [];
  82785. for (i = 0; i < this.triangles.length; ++i) {
  82786. if (!this.triangles[i].deleted) {
  82787. newTrianglesVector.push(this.triangles[i]);
  82788. }
  82789. }
  82790. this.triangles = newTrianglesVector;
  82791. }
  82792. for (i = 0; i < this.vertices.length; ++i) {
  82793. this.vertices[i].triangleCount = 0;
  82794. this.vertices[i].triangleStart = 0;
  82795. }
  82796. var t;
  82797. var j;
  82798. var v;
  82799. for (i = 0; i < this.triangles.length; ++i) {
  82800. t = this.triangles[i];
  82801. for (j = 0; j < 3; ++j) {
  82802. v = t.vertices[j];
  82803. v.triangleCount++;
  82804. }
  82805. }
  82806. var tStart = 0;
  82807. for (i = 0; i < this.vertices.length; ++i) {
  82808. this.vertices[i].triangleStart = tStart;
  82809. tStart += this.vertices[i].triangleCount;
  82810. this.vertices[i].triangleCount = 0;
  82811. }
  82812. var newReferences = new Array(this.triangles.length * 3);
  82813. for (i = 0; i < this.triangles.length; ++i) {
  82814. t = this.triangles[i];
  82815. for (j = 0; j < 3; ++j) {
  82816. v = t.vertices[j];
  82817. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  82818. v.triangleCount++;
  82819. }
  82820. }
  82821. this.references = newReferences;
  82822. if (identifyBorders) {
  82823. this.identifyBorder();
  82824. }
  82825. };
  82826. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  82827. var x = point.x;
  82828. var y = point.y;
  82829. var z = point.z;
  82830. 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
  82831. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  82832. };
  82833. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  82834. var q = vertex1.q.add(vertex2.q);
  82835. var border = vertex1.isBorder && vertex2.isBorder;
  82836. var error = 0;
  82837. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  82838. if (qDet !== 0 && !border) {
  82839. if (!pointResult) {
  82840. pointResult = BABYLON.Vector3.Zero();
  82841. }
  82842. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  82843. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  82844. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  82845. error = this.vertexError(q, pointResult);
  82846. }
  82847. else {
  82848. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  82849. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  82850. var error1 = this.vertexError(q, vertex1.position);
  82851. var error2 = this.vertexError(q, vertex2.position);
  82852. var error3 = this.vertexError(q, p3);
  82853. error = Math.min(error1, error2, error3);
  82854. if (error === error1) {
  82855. if (pointResult) {
  82856. pointResult.copyFrom(vertex1.position);
  82857. }
  82858. }
  82859. else if (error === error2) {
  82860. if (pointResult) {
  82861. pointResult.copyFrom(vertex2.position);
  82862. }
  82863. }
  82864. else {
  82865. if (pointResult) {
  82866. pointResult.copyFrom(p3);
  82867. }
  82868. }
  82869. }
  82870. return error;
  82871. };
  82872. return QuadraticErrorSimplification;
  82873. }());
  82874. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  82875. })(BABYLON || (BABYLON = {}));
  82876. //# sourceMappingURL=babylon.meshSimplification.js.map
  82877. var BABYLON;
  82878. (function (BABYLON) {
  82879. var MeshLODLevel = /** @class */ (function () {
  82880. function MeshLODLevel(distance, mesh) {
  82881. this.distance = distance;
  82882. this.mesh = mesh;
  82883. }
  82884. return MeshLODLevel;
  82885. }());
  82886. BABYLON.MeshLODLevel = MeshLODLevel;
  82887. })(BABYLON || (BABYLON = {}));
  82888. //# sourceMappingURL=babylon.meshLODLevel.js.map
  82889. var BABYLON;
  82890. (function (BABYLON) {
  82891. /**
  82892. * Defines the root class used to create scene optimization to use with SceneOptimizer
  82893. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82894. */
  82895. var SceneOptimization = /** @class */ (function () {
  82896. /**
  82897. * Creates the SceneOptimization object
  82898. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  82899. * @param desc defines the description associated with the optimization
  82900. */
  82901. function SceneOptimization(
  82902. /**
  82903. * Defines the priority of this optimization (0 by default which means first in the list)
  82904. */
  82905. priority) {
  82906. if (priority === void 0) { priority = 0; }
  82907. this.priority = priority;
  82908. }
  82909. /**
  82910. * Gets a string describing the action executed by the current optimization
  82911. * @returns description string
  82912. */
  82913. SceneOptimization.prototype.getDescription = function () {
  82914. return "";
  82915. };
  82916. /**
  82917. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82918. * @param scene defines the current scene where to apply this optimization
  82919. * @param optimizer defines the current optimizer
  82920. * @returns true if everything that can be done was applied
  82921. */
  82922. SceneOptimization.prototype.apply = function (scene, optimizer) {
  82923. return true;
  82924. };
  82925. ;
  82926. return SceneOptimization;
  82927. }());
  82928. BABYLON.SceneOptimization = SceneOptimization;
  82929. /**
  82930. * Defines an optimization used to reduce the size of render target textures
  82931. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82932. */
  82933. var TextureOptimization = /** @class */ (function (_super) {
  82934. __extends(TextureOptimization, _super);
  82935. /**
  82936. * Creates the TextureOptimization object
  82937. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  82938. * @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
  82939. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  82940. */
  82941. function TextureOptimization(
  82942. /**
  82943. * Defines the priority of this optimization (0 by default which means first in the list)
  82944. */
  82945. priority,
  82946. /**
  82947. * 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
  82948. */
  82949. maximumSize,
  82950. /**
  82951. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  82952. */
  82953. step) {
  82954. if (priority === void 0) { priority = 0; }
  82955. if (maximumSize === void 0) { maximumSize = 1024; }
  82956. if (step === void 0) { step = 0.5; }
  82957. var _this = _super.call(this, priority) || this;
  82958. _this.priority = priority;
  82959. _this.maximumSize = maximumSize;
  82960. _this.step = step;
  82961. return _this;
  82962. }
  82963. /**
  82964. * Gets a string describing the action executed by the current optimization
  82965. * @returns description string
  82966. */
  82967. TextureOptimization.prototype.getDescription = function () {
  82968. return "Reducing render target texture size to " + this.maximumSize;
  82969. };
  82970. /**
  82971. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82972. * @param scene defines the current scene where to apply this optimization
  82973. * @param optimizer defines the current optimizer
  82974. * @returns true if everything that can be done was applied
  82975. */
  82976. TextureOptimization.prototype.apply = function (scene, optimizer) {
  82977. var allDone = true;
  82978. for (var index = 0; index < scene.textures.length; index++) {
  82979. var texture = scene.textures[index];
  82980. if (!texture.canRescale || texture.getContext) {
  82981. continue;
  82982. }
  82983. var currentSize = texture.getSize();
  82984. var maxDimension = Math.max(currentSize.width, currentSize.height);
  82985. if (maxDimension > this.maximumSize) {
  82986. texture.scale(this.step);
  82987. allDone = false;
  82988. }
  82989. }
  82990. return allDone;
  82991. };
  82992. return TextureOptimization;
  82993. }(SceneOptimization));
  82994. BABYLON.TextureOptimization = TextureOptimization;
  82995. /**
  82996. * Defines an optimization used to increase or decrease the rendering resolution
  82997. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82998. */
  82999. var HardwareScalingOptimization = /** @class */ (function (_super) {
  83000. __extends(HardwareScalingOptimization, _super);
  83001. /**
  83002. * Creates the HardwareScalingOptimization object
  83003. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83004. * @param maximumScale defines the maximum scale to use (2 by default)
  83005. * @param step defines the step to use between two passes (0.5 by default)
  83006. */
  83007. function HardwareScalingOptimization(
  83008. /**
  83009. * Defines the priority of this optimization (0 by default which means first in the list)
  83010. */
  83011. priority,
  83012. /**
  83013. * Defines the maximum scale to use (2 by default)
  83014. */
  83015. maximumScale,
  83016. /**
  83017. * Defines the step to use between two passes (0.5 by default)
  83018. */
  83019. step) {
  83020. if (priority === void 0) { priority = 0; }
  83021. if (maximumScale === void 0) { maximumScale = 2; }
  83022. if (step === void 0) { step = 0.25; }
  83023. var _this = _super.call(this, priority) || this;
  83024. _this.priority = priority;
  83025. _this.maximumScale = maximumScale;
  83026. _this.step = step;
  83027. _this._currentScale = -1;
  83028. _this._directionOffset = 1;
  83029. return _this;
  83030. }
  83031. /**
  83032. * Gets a string describing the action executed by the current optimization
  83033. * @return description string
  83034. */
  83035. HardwareScalingOptimization.prototype.getDescription = function () {
  83036. return "Setting hardware scaling level to " + this._currentScale;
  83037. };
  83038. /**
  83039. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83040. * @param scene defines the current scene where to apply this optimization
  83041. * @param optimizer defines the current optimizer
  83042. * @returns true if everything that can be done was applied
  83043. */
  83044. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  83045. if (this._currentScale === -1) {
  83046. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  83047. if (this._currentScale > this.maximumScale) {
  83048. this._directionOffset = -1;
  83049. }
  83050. }
  83051. this._currentScale += this._directionOffset * this.step;
  83052. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  83053. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  83054. };
  83055. ;
  83056. return HardwareScalingOptimization;
  83057. }(SceneOptimization));
  83058. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  83059. /**
  83060. * Defines an optimization used to remove shadows
  83061. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83062. */
  83063. var ShadowsOptimization = /** @class */ (function (_super) {
  83064. __extends(ShadowsOptimization, _super);
  83065. function ShadowsOptimization() {
  83066. return _super !== null && _super.apply(this, arguments) || this;
  83067. }
  83068. /**
  83069. * Gets a string describing the action executed by the current optimization
  83070. * @return description string
  83071. */
  83072. ShadowsOptimization.prototype.getDescription = function () {
  83073. return "Turning shadows on/off";
  83074. };
  83075. /**
  83076. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83077. * @param scene defines the current scene where to apply this optimization
  83078. * @param optimizer defines the current optimizer
  83079. * @returns true if everything that can be done was applied
  83080. */
  83081. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  83082. scene.shadowsEnabled = optimizer.isInImprovementMode;
  83083. return true;
  83084. };
  83085. ;
  83086. return ShadowsOptimization;
  83087. }(SceneOptimization));
  83088. BABYLON.ShadowsOptimization = ShadowsOptimization;
  83089. /**
  83090. * Defines an optimization used to turn post-processes off
  83091. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83092. */
  83093. var PostProcessesOptimization = /** @class */ (function (_super) {
  83094. __extends(PostProcessesOptimization, _super);
  83095. function PostProcessesOptimization() {
  83096. return _super !== null && _super.apply(this, arguments) || this;
  83097. }
  83098. /**
  83099. * Gets a string describing the action executed by the current optimization
  83100. * @return description string
  83101. */
  83102. PostProcessesOptimization.prototype.getDescription = function () {
  83103. return "Turning post-processes on/off";
  83104. };
  83105. /**
  83106. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83107. * @param scene defines the current scene where to apply this optimization
  83108. * @param optimizer defines the current optimizer
  83109. * @returns true if everything that can be done was applied
  83110. */
  83111. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  83112. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  83113. return true;
  83114. };
  83115. ;
  83116. return PostProcessesOptimization;
  83117. }(SceneOptimization));
  83118. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  83119. /**
  83120. * Defines an optimization used to turn lens flares off
  83121. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83122. */
  83123. var LensFlaresOptimization = /** @class */ (function (_super) {
  83124. __extends(LensFlaresOptimization, _super);
  83125. function LensFlaresOptimization() {
  83126. return _super !== null && _super.apply(this, arguments) || this;
  83127. }
  83128. /**
  83129. * Gets a string describing the action executed by the current optimization
  83130. * @return description string
  83131. */
  83132. LensFlaresOptimization.prototype.getDescription = function () {
  83133. return "Turning lens flares on/off";
  83134. };
  83135. /**
  83136. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83137. * @param scene defines the current scene where to apply this optimization
  83138. * @param optimizer defines the current optimizer
  83139. * @returns true if everything that can be done was applied
  83140. */
  83141. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  83142. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  83143. return true;
  83144. };
  83145. ;
  83146. return LensFlaresOptimization;
  83147. }(SceneOptimization));
  83148. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  83149. /**
  83150. * Defines an optimization based on user defined callback.
  83151. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83152. */
  83153. var CustomOptimization = /** @class */ (function (_super) {
  83154. __extends(CustomOptimization, _super);
  83155. function CustomOptimization() {
  83156. return _super !== null && _super.apply(this, arguments) || this;
  83157. }
  83158. /**
  83159. * Gets a string describing the action executed by the current optimization
  83160. * @returns description string
  83161. */
  83162. CustomOptimization.prototype.getDescription = function () {
  83163. if (this.onGetDescription) {
  83164. return this.onGetDescription();
  83165. }
  83166. return "Running user defined callback";
  83167. };
  83168. /**
  83169. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83170. * @param scene defines the current scene where to apply this optimization
  83171. * @param optimizer defines the current optimizer
  83172. * @returns true if everything that can be done was applied
  83173. */
  83174. CustomOptimization.prototype.apply = function (scene, optimizer) {
  83175. if (this.onApply) {
  83176. return this.onApply(scene, optimizer);
  83177. }
  83178. return true;
  83179. };
  83180. ;
  83181. return CustomOptimization;
  83182. }(SceneOptimization));
  83183. BABYLON.CustomOptimization = CustomOptimization;
  83184. /**
  83185. * Defines an optimization used to turn particles off
  83186. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83187. */
  83188. var ParticlesOptimization = /** @class */ (function (_super) {
  83189. __extends(ParticlesOptimization, _super);
  83190. function ParticlesOptimization() {
  83191. return _super !== null && _super.apply(this, arguments) || this;
  83192. }
  83193. /**
  83194. * Gets a string describing the action executed by the current optimization
  83195. * @return description string
  83196. */
  83197. ParticlesOptimization.prototype.getDescription = function () {
  83198. return "Turning particles on/off";
  83199. };
  83200. /**
  83201. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83202. * @param scene defines the current scene where to apply this optimization
  83203. * @param optimizer defines the current optimizer
  83204. * @returns true if everything that can be done was applied
  83205. */
  83206. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  83207. scene.particlesEnabled = optimizer.isInImprovementMode;
  83208. return true;
  83209. };
  83210. ;
  83211. return ParticlesOptimization;
  83212. }(SceneOptimization));
  83213. BABYLON.ParticlesOptimization = ParticlesOptimization;
  83214. /**
  83215. * Defines an optimization used to turn render targets off
  83216. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83217. */
  83218. var RenderTargetsOptimization = /** @class */ (function (_super) {
  83219. __extends(RenderTargetsOptimization, _super);
  83220. function RenderTargetsOptimization() {
  83221. return _super !== null && _super.apply(this, arguments) || this;
  83222. }
  83223. /**
  83224. * Gets a string describing the action executed by the current optimization
  83225. * @return description string
  83226. */
  83227. RenderTargetsOptimization.prototype.getDescription = function () {
  83228. return "Turning render targets off";
  83229. };
  83230. /**
  83231. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83232. * @param scene defines the current scene where to apply this optimization
  83233. * @param optimizer defines the current optimizer
  83234. * @returns true if everything that can be done was applied
  83235. */
  83236. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  83237. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  83238. return true;
  83239. };
  83240. ;
  83241. return RenderTargetsOptimization;
  83242. }(SceneOptimization));
  83243. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  83244. /**
  83245. * Defines an optimization used to merge meshes with compatible materials
  83246. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83247. */
  83248. var MergeMeshesOptimization = /** @class */ (function (_super) {
  83249. __extends(MergeMeshesOptimization, _super);
  83250. function MergeMeshesOptimization() {
  83251. var _this = _super !== null && _super.apply(this, arguments) || this;
  83252. _this._canBeMerged = function (abstractMesh) {
  83253. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  83254. return false;
  83255. }
  83256. var mesh = abstractMesh;
  83257. if (!mesh.isVisible || !mesh.isEnabled()) {
  83258. return false;
  83259. }
  83260. if (mesh.instances.length > 0) {
  83261. return false;
  83262. }
  83263. if (mesh.skeleton || mesh.hasLODLevels) {
  83264. return false;
  83265. }
  83266. if (mesh.parent) {
  83267. return false;
  83268. }
  83269. return true;
  83270. };
  83271. return _this;
  83272. }
  83273. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  83274. /**
  83275. * Gets or sets a boolean which defines if optimization octree has to be updated
  83276. */
  83277. get: function () {
  83278. return MergeMeshesOptimization._UpdateSelectionTree;
  83279. },
  83280. /**
  83281. * Gets or sets a boolean which defines if optimization octree has to be updated
  83282. */
  83283. set: function (value) {
  83284. MergeMeshesOptimization._UpdateSelectionTree = value;
  83285. },
  83286. enumerable: true,
  83287. configurable: true
  83288. });
  83289. /**
  83290. * Gets a string describing the action executed by the current optimization
  83291. * @return description string
  83292. */
  83293. MergeMeshesOptimization.prototype.getDescription = function () {
  83294. return "Merging similar meshes together";
  83295. };
  83296. /**
  83297. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83298. * @param scene defines the current scene where to apply this optimization
  83299. * @param optimizer defines the current optimizer
  83300. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  83301. * @returns true if everything that can be done was applied
  83302. */
  83303. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  83304. var globalPool = scene.meshes.slice(0);
  83305. var globalLength = globalPool.length;
  83306. for (var index = 0; index < globalLength; index++) {
  83307. var currentPool = new Array();
  83308. var current = globalPool[index];
  83309. // Checks
  83310. if (!this._canBeMerged(current)) {
  83311. continue;
  83312. }
  83313. currentPool.push(current);
  83314. // Find compatible meshes
  83315. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  83316. var otherMesh = globalPool[subIndex];
  83317. if (!this._canBeMerged(otherMesh)) {
  83318. continue;
  83319. }
  83320. if (otherMesh.material !== current.material) {
  83321. continue;
  83322. }
  83323. if (otherMesh.checkCollisions !== current.checkCollisions) {
  83324. continue;
  83325. }
  83326. currentPool.push(otherMesh);
  83327. globalLength--;
  83328. globalPool.splice(subIndex, 1);
  83329. subIndex--;
  83330. }
  83331. if (currentPool.length < 2) {
  83332. continue;
  83333. }
  83334. // Merge meshes
  83335. BABYLON.Mesh.MergeMeshes(currentPool);
  83336. }
  83337. if (updateSelectionTree != undefined) {
  83338. if (updateSelectionTree) {
  83339. scene.createOrUpdateSelectionOctree();
  83340. }
  83341. }
  83342. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  83343. scene.createOrUpdateSelectionOctree();
  83344. }
  83345. return true;
  83346. };
  83347. ;
  83348. MergeMeshesOptimization._UpdateSelectionTree = false;
  83349. return MergeMeshesOptimization;
  83350. }(SceneOptimization));
  83351. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  83352. /**
  83353. * Defines a list of options used by SceneOptimizer
  83354. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83355. */
  83356. var SceneOptimizerOptions = /** @class */ (function () {
  83357. /**
  83358. * Creates a new list of options used by SceneOptimizer
  83359. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  83360. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  83361. */
  83362. function SceneOptimizerOptions(
  83363. /**
  83364. * Defines the target frame rate to reach (60 by default)
  83365. */
  83366. targetFrameRate,
  83367. /**
  83368. * Defines the interval between two checkes (2000ms by default)
  83369. */
  83370. trackerDuration) {
  83371. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  83372. if (trackerDuration === void 0) { trackerDuration = 2000; }
  83373. this.targetFrameRate = targetFrameRate;
  83374. this.trackerDuration = trackerDuration;
  83375. /**
  83376. * Gets the list of optimizations to apply
  83377. */
  83378. this.optimizations = new Array();
  83379. }
  83380. /**
  83381. * Add a new optimization
  83382. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  83383. * @returns the current SceneOptimizerOptions
  83384. */
  83385. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  83386. this.optimizations.push(optimization);
  83387. return this;
  83388. };
  83389. /**
  83390. * Add a new custom optimization
  83391. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  83392. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  83393. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83394. * @returns the current SceneOptimizerOptions
  83395. */
  83396. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  83397. if (priority === void 0) { priority = 0; }
  83398. var optimization = new CustomOptimization(priority);
  83399. optimization.onApply = onApply;
  83400. optimization.onGetDescription = onGetDescription;
  83401. this.optimizations.push(optimization);
  83402. return this;
  83403. };
  83404. /**
  83405. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  83406. * @param targetFrameRate defines the target frame rate (60 by default)
  83407. * @returns a SceneOptimizerOptions object
  83408. */
  83409. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  83410. var result = new SceneOptimizerOptions(targetFrameRate);
  83411. var priority = 0;
  83412. result.addOptimization(new MergeMeshesOptimization(priority));
  83413. result.addOptimization(new ShadowsOptimization(priority));
  83414. result.addOptimization(new LensFlaresOptimization(priority));
  83415. // Next priority
  83416. priority++;
  83417. result.addOptimization(new PostProcessesOptimization(priority));
  83418. result.addOptimization(new ParticlesOptimization(priority));
  83419. // Next priority
  83420. priority++;
  83421. result.addOptimization(new TextureOptimization(priority, 1024));
  83422. return result;
  83423. };
  83424. /**
  83425. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  83426. * @param targetFrameRate defines the target frame rate (60 by default)
  83427. * @returns a SceneOptimizerOptions object
  83428. */
  83429. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  83430. var result = new SceneOptimizerOptions(targetFrameRate);
  83431. var priority = 0;
  83432. result.addOptimization(new MergeMeshesOptimization(priority));
  83433. result.addOptimization(new ShadowsOptimization(priority));
  83434. result.addOptimization(new LensFlaresOptimization(priority));
  83435. // Next priority
  83436. priority++;
  83437. result.addOptimization(new PostProcessesOptimization(priority));
  83438. result.addOptimization(new ParticlesOptimization(priority));
  83439. // Next priority
  83440. priority++;
  83441. result.addOptimization(new TextureOptimization(priority, 512));
  83442. // Next priority
  83443. priority++;
  83444. result.addOptimization(new RenderTargetsOptimization(priority));
  83445. // Next priority
  83446. priority++;
  83447. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  83448. return result;
  83449. };
  83450. /**
  83451. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  83452. * @param targetFrameRate defines the target frame rate (60 by default)
  83453. * @returns a SceneOptimizerOptions object
  83454. */
  83455. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  83456. var result = new SceneOptimizerOptions(targetFrameRate);
  83457. var priority = 0;
  83458. result.addOptimization(new MergeMeshesOptimization(priority));
  83459. result.addOptimization(new ShadowsOptimization(priority));
  83460. result.addOptimization(new LensFlaresOptimization(priority));
  83461. // Next priority
  83462. priority++;
  83463. result.addOptimization(new PostProcessesOptimization(priority));
  83464. result.addOptimization(new ParticlesOptimization(priority));
  83465. // Next priority
  83466. priority++;
  83467. result.addOptimization(new TextureOptimization(priority, 256));
  83468. // Next priority
  83469. priority++;
  83470. result.addOptimization(new RenderTargetsOptimization(priority));
  83471. // Next priority
  83472. priority++;
  83473. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  83474. return result;
  83475. };
  83476. return SceneOptimizerOptions;
  83477. }());
  83478. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  83479. /**
  83480. * Class used to run optimizations in order to reach a target frame rate
  83481. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83482. */
  83483. var SceneOptimizer = /** @class */ (function () {
  83484. /**
  83485. * Creates a new SceneOptimizer
  83486. * @param scene defines the scene to work on
  83487. * @param options defines the options to use with the SceneOptimizer
  83488. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  83489. * @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)
  83490. */
  83491. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  83492. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  83493. if (improvementMode === void 0) { improvementMode = false; }
  83494. var _this = this;
  83495. this._isRunning = false;
  83496. this._currentPriorityLevel = 0;
  83497. this._targetFrameRate = 60;
  83498. this._trackerDuration = 2000;
  83499. this._currentFrameRate = 0;
  83500. this._improvementMode = false;
  83501. /**
  83502. * Defines an observable called when the optimizer reaches the target frame rate
  83503. */
  83504. this.onSuccessObservable = new BABYLON.Observable();
  83505. /**
  83506. * Defines an observable called when the optimizer enables an optimization
  83507. */
  83508. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  83509. /**
  83510. * Defines an observable called when the optimizer is not able to reach the target frame rate
  83511. */
  83512. this.onFailureObservable = new BABYLON.Observable();
  83513. if (!options) {
  83514. this._options = new SceneOptimizerOptions();
  83515. }
  83516. else {
  83517. this._options = options;
  83518. }
  83519. if (this._options.targetFrameRate) {
  83520. this._targetFrameRate = this._options.targetFrameRate;
  83521. }
  83522. if (this._options.trackerDuration) {
  83523. this._trackerDuration = this._options.trackerDuration;
  83524. }
  83525. if (autoGeneratePriorities) {
  83526. var priority = 0;
  83527. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  83528. var optim = _a[_i];
  83529. optim.priority = priority++;
  83530. }
  83531. }
  83532. this._improvementMode = improvementMode;
  83533. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83534. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  83535. _this._sceneDisposeObserver = null;
  83536. _this.dispose();
  83537. });
  83538. }
  83539. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  83540. /**
  83541. * Gets a boolean indicating if the optimizer is in improvement mode
  83542. */
  83543. get: function () {
  83544. return this._improvementMode;
  83545. },
  83546. enumerable: true,
  83547. configurable: true
  83548. });
  83549. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  83550. /**
  83551. * Gets the current priority level (0 at start)
  83552. */
  83553. get: function () {
  83554. return this._currentPriorityLevel;
  83555. },
  83556. enumerable: true,
  83557. configurable: true
  83558. });
  83559. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  83560. /**
  83561. * Gets the current frame rate checked by the SceneOptimizer
  83562. */
  83563. get: function () {
  83564. return this._currentFrameRate;
  83565. },
  83566. enumerable: true,
  83567. configurable: true
  83568. });
  83569. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  83570. /**
  83571. * Gets or sets the current target frame rate (60 by default)
  83572. */
  83573. get: function () {
  83574. return this._targetFrameRate;
  83575. },
  83576. /**
  83577. * Gets or sets the current target frame rate (60 by default)
  83578. */
  83579. set: function (value) {
  83580. this._targetFrameRate = value;
  83581. },
  83582. enumerable: true,
  83583. configurable: true
  83584. });
  83585. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  83586. /**
  83587. * Gets or sets the current interval between two checks (every 2000ms by default)
  83588. */
  83589. get: function () {
  83590. return this._trackerDuration;
  83591. },
  83592. /**
  83593. * Gets or sets the current interval between two checks (every 2000ms by default)
  83594. */
  83595. set: function (value) {
  83596. this._trackerDuration = value;
  83597. },
  83598. enumerable: true,
  83599. configurable: true
  83600. });
  83601. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  83602. /**
  83603. * Gets the list of active optimizations
  83604. */
  83605. get: function () {
  83606. return this._options.optimizations;
  83607. },
  83608. enumerable: true,
  83609. configurable: true
  83610. });
  83611. /**
  83612. * Stops the current optimizer
  83613. */
  83614. SceneOptimizer.prototype.stop = function () {
  83615. this._isRunning = false;
  83616. };
  83617. /**
  83618. * Reset the optimizer to initial step (current priority level = 0)
  83619. */
  83620. SceneOptimizer.prototype.reset = function () {
  83621. this._currentPriorityLevel = 0;
  83622. };
  83623. /**
  83624. * Start the optimizer. By default it will try to reach a specific framerate
  83625. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  83626. */
  83627. SceneOptimizer.prototype.start = function () {
  83628. var _this = this;
  83629. if (this._isRunning) {
  83630. return;
  83631. }
  83632. this._isRunning = true;
  83633. // Let's wait for the scene to be ready before running our check
  83634. this._scene.executeWhenReady(function () {
  83635. setTimeout(function () {
  83636. _this._checkCurrentState();
  83637. }, _this._trackerDuration);
  83638. });
  83639. };
  83640. SceneOptimizer.prototype._checkCurrentState = function () {
  83641. var _this = this;
  83642. if (!this._isRunning) {
  83643. return;
  83644. }
  83645. var scene = this._scene;
  83646. var options = this._options;
  83647. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  83648. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  83649. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  83650. this._isRunning = false;
  83651. this.onSuccessObservable.notifyObservers(this);
  83652. return;
  83653. }
  83654. // Apply current level of optimizations
  83655. var allDone = true;
  83656. var noOptimizationApplied = true;
  83657. for (var index = 0; index < options.optimizations.length; index++) {
  83658. var optimization = options.optimizations[index];
  83659. if (optimization.priority === this._currentPriorityLevel) {
  83660. noOptimizationApplied = false;
  83661. allDone = allDone && optimization.apply(scene, this);
  83662. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  83663. }
  83664. }
  83665. // If no optimization was applied, this is a failure :(
  83666. if (noOptimizationApplied) {
  83667. this._isRunning = false;
  83668. this.onFailureObservable.notifyObservers(this);
  83669. return;
  83670. }
  83671. // If all optimizations were done, move to next level
  83672. if (allDone) {
  83673. this._currentPriorityLevel++;
  83674. }
  83675. // Let's the system running for a specific amount of time before checking FPS
  83676. scene.executeWhenReady(function () {
  83677. setTimeout(function () {
  83678. _this._checkCurrentState();
  83679. }, _this._trackerDuration);
  83680. });
  83681. };
  83682. /**
  83683. * Release all resources
  83684. */
  83685. SceneOptimizer.prototype.dispose = function () {
  83686. this.stop();
  83687. this.onSuccessObservable.clear();
  83688. this.onFailureObservable.clear();
  83689. this.onNewOptimizationAppliedObservable.clear();
  83690. if (this._sceneDisposeObserver) {
  83691. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  83692. }
  83693. };
  83694. /**
  83695. * Helper function to create a SceneOptimizer with one single line of code
  83696. * @param scene defines the scene to work on
  83697. * @param options defines the options to use with the SceneOptimizer
  83698. * @param onSuccess defines a callback to call on success
  83699. * @param onFailure defines a callback to call on failure
  83700. * @returns the new SceneOptimizer object
  83701. */
  83702. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  83703. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  83704. if (onSuccess) {
  83705. optimizer.onSuccessObservable.add(function () {
  83706. onSuccess();
  83707. });
  83708. }
  83709. if (onFailure) {
  83710. optimizer.onFailureObservable.add(function () {
  83711. onFailure();
  83712. });
  83713. }
  83714. optimizer.start();
  83715. return optimizer;
  83716. };
  83717. return SceneOptimizer;
  83718. }());
  83719. BABYLON.SceneOptimizer = SceneOptimizer;
  83720. })(BABYLON || (BABYLON = {}));
  83721. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  83722. var BABYLON;
  83723. (function (BABYLON) {
  83724. var OutlineRenderer = /** @class */ (function () {
  83725. function OutlineRenderer(scene) {
  83726. this.zOffset = 1;
  83727. this._scene = scene;
  83728. }
  83729. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  83730. var _this = this;
  83731. if (useOverlay === void 0) { useOverlay = false; }
  83732. var scene = this._scene;
  83733. var engine = this._scene.getEngine();
  83734. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  83735. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  83736. return;
  83737. }
  83738. var mesh = subMesh.getRenderingMesh();
  83739. var material = subMesh.getMaterial();
  83740. if (!material || !scene.activeCamera) {
  83741. return;
  83742. }
  83743. engine.enableEffect(this._effect);
  83744. // Logarithmic depth
  83745. if (material.useLogarithmicDepth) {
  83746. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  83747. }
  83748. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  83749. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  83750. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  83751. // Bones
  83752. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  83753. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  83754. }
  83755. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  83756. // Alpha test
  83757. if (material && material.needAlphaTesting()) {
  83758. var alphaTexture = material.getAlphaTestTexture();
  83759. if (alphaTexture) {
  83760. this._effect.setTexture("diffuseSampler", alphaTexture);
  83761. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  83762. }
  83763. }
  83764. engine.setZOffset(-this.zOffset);
  83765. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  83766. engine.setZOffset(0);
  83767. };
  83768. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  83769. var defines = [];
  83770. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  83771. var mesh = subMesh.getMesh();
  83772. var material = subMesh.getMaterial();
  83773. if (material) {
  83774. // Alpha test
  83775. if (material.needAlphaTesting()) {
  83776. defines.push("#define ALPHATEST");
  83777. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83778. attribs.push(BABYLON.VertexBuffer.UVKind);
  83779. defines.push("#define UV1");
  83780. }
  83781. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  83782. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83783. defines.push("#define UV2");
  83784. }
  83785. }
  83786. //Logarithmic depth
  83787. if (material.useLogarithmicDepth) {
  83788. defines.push("#define LOGARITHMICDEPTH");
  83789. }
  83790. }
  83791. // Bones
  83792. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83793. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83794. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83795. if (mesh.numBoneInfluencers > 4) {
  83796. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  83797. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  83798. }
  83799. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83800. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  83801. }
  83802. else {
  83803. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83804. }
  83805. // Instances
  83806. if (useInstances) {
  83807. defines.push("#define INSTANCES");
  83808. attribs.push("world0");
  83809. attribs.push("world1");
  83810. attribs.push("world2");
  83811. attribs.push("world3");
  83812. }
  83813. // Get correct effect
  83814. var join = defines.join("\n");
  83815. if (this._cachedDefines !== join) {
  83816. this._cachedDefines = join;
  83817. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  83818. }
  83819. return this._effect.isReady();
  83820. };
  83821. return OutlineRenderer;
  83822. }());
  83823. BABYLON.OutlineRenderer = OutlineRenderer;
  83824. })(BABYLON || (BABYLON = {}));
  83825. //# sourceMappingURL=babylon.outlineRenderer.js.map
  83826. var BABYLON;
  83827. (function (BABYLON) {
  83828. var FaceAdjacencies = /** @class */ (function () {
  83829. function FaceAdjacencies() {
  83830. this.edges = new Array();
  83831. this.edgesConnectedCount = 0;
  83832. }
  83833. return FaceAdjacencies;
  83834. }());
  83835. var EdgesRenderer = /** @class */ (function () {
  83836. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  83837. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  83838. if (epsilon === void 0) { epsilon = 0.95; }
  83839. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  83840. this.edgesWidthScalerForOrthographic = 1000.0;
  83841. this.edgesWidthScalerForPerspective = 50.0;
  83842. this._linesPositions = new Array();
  83843. this._linesNormals = new Array();
  83844. this._linesIndices = new Array();
  83845. this._buffers = {};
  83846. this._checkVerticesInsteadOfIndices = false;
  83847. this._source = source;
  83848. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  83849. this._epsilon = epsilon;
  83850. this._prepareRessources();
  83851. this._generateEdgesLines();
  83852. }
  83853. EdgesRenderer.prototype._prepareRessources = function () {
  83854. if (this._lineShader) {
  83855. return;
  83856. }
  83857. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  83858. attributes: ["position", "normal"],
  83859. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  83860. });
  83861. this._lineShader.disableDepthWrite = true;
  83862. this._lineShader.backFaceCulling = false;
  83863. };
  83864. EdgesRenderer.prototype._rebuild = function () {
  83865. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  83866. if (buffer) {
  83867. buffer._rebuild();
  83868. }
  83869. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  83870. if (buffer) {
  83871. buffer._rebuild();
  83872. }
  83873. var scene = this._source.getScene();
  83874. var engine = scene.getEngine();
  83875. this._ib = engine.createIndexBuffer(this._linesIndices);
  83876. };
  83877. EdgesRenderer.prototype.dispose = function () {
  83878. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  83879. if (buffer) {
  83880. buffer.dispose();
  83881. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  83882. }
  83883. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  83884. if (buffer) {
  83885. buffer.dispose();
  83886. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  83887. }
  83888. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  83889. this._lineShader.dispose();
  83890. };
  83891. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  83892. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  83893. return 0;
  83894. }
  83895. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  83896. return 1;
  83897. }
  83898. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  83899. return 2;
  83900. }
  83901. return -1;
  83902. };
  83903. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  83904. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  83905. return 0;
  83906. }
  83907. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  83908. return 1;
  83909. }
  83910. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  83911. return 2;
  83912. }
  83913. return -1;
  83914. };
  83915. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  83916. var needToCreateLine;
  83917. if (edge === undefined) {
  83918. needToCreateLine = true;
  83919. }
  83920. else {
  83921. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  83922. needToCreateLine = dotProduct < this._epsilon;
  83923. }
  83924. if (needToCreateLine) {
  83925. var offset = this._linesPositions.length / 3;
  83926. var normal = p0.subtract(p1);
  83927. normal.normalize();
  83928. // Positions
  83929. this._linesPositions.push(p0.x);
  83930. this._linesPositions.push(p0.y);
  83931. this._linesPositions.push(p0.z);
  83932. this._linesPositions.push(p0.x);
  83933. this._linesPositions.push(p0.y);
  83934. this._linesPositions.push(p0.z);
  83935. this._linesPositions.push(p1.x);
  83936. this._linesPositions.push(p1.y);
  83937. this._linesPositions.push(p1.z);
  83938. this._linesPositions.push(p1.x);
  83939. this._linesPositions.push(p1.y);
  83940. this._linesPositions.push(p1.z);
  83941. // Normals
  83942. this._linesNormals.push(p1.x);
  83943. this._linesNormals.push(p1.y);
  83944. this._linesNormals.push(p1.z);
  83945. this._linesNormals.push(-1);
  83946. this._linesNormals.push(p1.x);
  83947. this._linesNormals.push(p1.y);
  83948. this._linesNormals.push(p1.z);
  83949. this._linesNormals.push(1);
  83950. this._linesNormals.push(p0.x);
  83951. this._linesNormals.push(p0.y);
  83952. this._linesNormals.push(p0.z);
  83953. this._linesNormals.push(-1);
  83954. this._linesNormals.push(p0.x);
  83955. this._linesNormals.push(p0.y);
  83956. this._linesNormals.push(p0.z);
  83957. this._linesNormals.push(1);
  83958. // Indices
  83959. this._linesIndices.push(offset);
  83960. this._linesIndices.push(offset + 1);
  83961. this._linesIndices.push(offset + 2);
  83962. this._linesIndices.push(offset);
  83963. this._linesIndices.push(offset + 2);
  83964. this._linesIndices.push(offset + 3);
  83965. }
  83966. };
  83967. EdgesRenderer.prototype._generateEdgesLines = function () {
  83968. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  83969. var indices = this._source.getIndices();
  83970. if (!indices || !positions) {
  83971. return;
  83972. }
  83973. // First let's find adjacencies
  83974. var adjacencies = new Array();
  83975. var faceNormals = new Array();
  83976. var index;
  83977. var faceAdjacencies;
  83978. // Prepare faces
  83979. for (index = 0; index < indices.length; index += 3) {
  83980. faceAdjacencies = new FaceAdjacencies();
  83981. var p0Index = indices[index];
  83982. var p1Index = indices[index + 1];
  83983. var p2Index = indices[index + 2];
  83984. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  83985. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  83986. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  83987. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  83988. faceNormal.normalize();
  83989. faceNormals.push(faceNormal);
  83990. adjacencies.push(faceAdjacencies);
  83991. }
  83992. // Scan
  83993. for (index = 0; index < adjacencies.length; index++) {
  83994. faceAdjacencies = adjacencies[index];
  83995. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  83996. var otherFaceAdjacencies = adjacencies[otherIndex];
  83997. if (faceAdjacencies.edgesConnectedCount === 3) {
  83998. break;
  83999. }
  84000. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  84001. continue;
  84002. }
  84003. var otherP0 = indices[otherIndex * 3];
  84004. var otherP1 = indices[otherIndex * 3 + 1];
  84005. var otherP2 = indices[otherIndex * 3 + 2];
  84006. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  84007. var otherEdgeIndex = 0;
  84008. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  84009. continue;
  84010. }
  84011. switch (edgeIndex) {
  84012. case 0:
  84013. if (this._checkVerticesInsteadOfIndices) {
  84014. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  84015. }
  84016. else {
  84017. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  84018. }
  84019. break;
  84020. case 1:
  84021. if (this._checkVerticesInsteadOfIndices) {
  84022. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  84023. }
  84024. else {
  84025. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  84026. }
  84027. break;
  84028. case 2:
  84029. if (this._checkVerticesInsteadOfIndices) {
  84030. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  84031. }
  84032. else {
  84033. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  84034. }
  84035. break;
  84036. }
  84037. if (otherEdgeIndex === -1) {
  84038. continue;
  84039. }
  84040. faceAdjacencies.edges[edgeIndex] = otherIndex;
  84041. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  84042. faceAdjacencies.edgesConnectedCount++;
  84043. otherFaceAdjacencies.edgesConnectedCount++;
  84044. if (faceAdjacencies.edgesConnectedCount === 3) {
  84045. break;
  84046. }
  84047. }
  84048. }
  84049. }
  84050. // Create lines
  84051. for (index = 0; index < adjacencies.length; index++) {
  84052. // 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
  84053. var current = adjacencies[index];
  84054. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  84055. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  84056. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  84057. }
  84058. // Merge into a single mesh
  84059. var engine = this._source.getScene().getEngine();
  84060. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  84061. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  84062. this._ib = engine.createIndexBuffer(this._linesIndices);
  84063. this._indicesCount = this._linesIndices.length;
  84064. };
  84065. EdgesRenderer.prototype.render = function () {
  84066. var scene = this._source.getScene();
  84067. if (!this._lineShader.isReady() || !scene.activeCamera) {
  84068. return;
  84069. }
  84070. var engine = scene.getEngine();
  84071. this._lineShader._preBind();
  84072. // VBOs
  84073. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  84074. scene.resetCachedMaterial();
  84075. this._lineShader.setColor4("color", this._source.edgesColor);
  84076. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  84077. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  84078. }
  84079. else {
  84080. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  84081. }
  84082. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  84083. this._lineShader.bind(this._source.getWorldMatrix());
  84084. // Draw order
  84085. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  84086. this._lineShader.unbind();
  84087. engine.setDepthWrite(true);
  84088. };
  84089. return EdgesRenderer;
  84090. }());
  84091. BABYLON.EdgesRenderer = EdgesRenderer;
  84092. })(BABYLON || (BABYLON = {}));
  84093. //# sourceMappingURL=babylon.edgesRenderer.js.map
  84094. var __assign = (this && this.__assign) || Object.assign || function(t) {
  84095. for (var s, i = 1, n = arguments.length; i < n; i++) {
  84096. s = arguments[i];
  84097. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  84098. t[p] = s[p];
  84099. }
  84100. return t;
  84101. };
  84102. var BABYLON;
  84103. (function (BABYLON) {
  84104. /**
  84105. * The effect layer Helps adding post process effect blended with the main pass.
  84106. *
  84107. * This can be for instance use to generate glow or higlight effects on the scene.
  84108. *
  84109. * The effect layer class can not be used directly and is intented to inherited from to be
  84110. * customized per effects.
  84111. */
  84112. var EffectLayer = /** @class */ (function () {
  84113. /**
  84114. * Instantiates a new effect Layer and references it in the scene.
  84115. * @param name The name of the layer
  84116. * @param scene The scene to use the layer in
  84117. */
  84118. function EffectLayer(
  84119. /** The Friendly of the effect in the scene */
  84120. name, scene) {
  84121. this.name = name;
  84122. this._vertexBuffers = {};
  84123. this._maxSize = 0;
  84124. this._mainTextureDesiredSize = { width: 0, height: 0 };
  84125. this._shouldRender = true;
  84126. this._postProcesses = [];
  84127. this._textures = [];
  84128. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  84129. /**
  84130. * The clear color of the texture used to generate the glow map.
  84131. */
  84132. this.neutralColor = new BABYLON.Color4();
  84133. /**
  84134. * Specifies wether the highlight layer is enabled or not.
  84135. */
  84136. this.isEnabled = true;
  84137. /**
  84138. * An event triggered when the effect layer has been disposed.
  84139. */
  84140. this.onDisposeObservable = new BABYLON.Observable();
  84141. /**
  84142. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  84143. */
  84144. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  84145. /**
  84146. * An event triggered when the generated texture is being merged in the scene.
  84147. */
  84148. this.onBeforeComposeObservable = new BABYLON.Observable();
  84149. /**
  84150. * An event triggered when the generated texture has been merged in the scene.
  84151. */
  84152. this.onAfterComposeObservable = new BABYLON.Observable();
  84153. /**
  84154. * An event triggered when the efffect layer changes its size.
  84155. */
  84156. this.onSizeChangedObservable = new BABYLON.Observable();
  84157. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84158. this._engine = scene.getEngine();
  84159. this._maxSize = this._engine.getCaps().maxTextureSize;
  84160. this._scene.effectLayers.push(this);
  84161. // Generate Buffers
  84162. this._generateIndexBuffer();
  84163. this._genrateVertexBuffer();
  84164. }
  84165. Object.defineProperty(EffectLayer.prototype, "camera", {
  84166. /**
  84167. * Gets the camera attached to the layer.
  84168. */
  84169. get: function () {
  84170. return this._effectLayerOptions.camera;
  84171. },
  84172. enumerable: true,
  84173. configurable: true
  84174. });
  84175. /**
  84176. * Initializes the effect layer with the required options.
  84177. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  84178. */
  84179. EffectLayer.prototype._init = function (options) {
  84180. // Adapt options
  84181. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  84182. this._setMainTextureSize();
  84183. this._createMainTexture();
  84184. this._createTextureAndPostProcesses();
  84185. this._mergeEffect = this._createMergeEffect();
  84186. };
  84187. /**
  84188. * Generates the index buffer of the full screen quad blending to the main canvas.
  84189. */
  84190. EffectLayer.prototype._generateIndexBuffer = function () {
  84191. // Indices
  84192. var indices = [];
  84193. indices.push(0);
  84194. indices.push(1);
  84195. indices.push(2);
  84196. indices.push(0);
  84197. indices.push(2);
  84198. indices.push(3);
  84199. this._indexBuffer = this._engine.createIndexBuffer(indices);
  84200. };
  84201. /**
  84202. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  84203. */
  84204. EffectLayer.prototype._genrateVertexBuffer = function () {
  84205. // VBO
  84206. var vertices = [];
  84207. vertices.push(1, 1);
  84208. vertices.push(-1, 1);
  84209. vertices.push(-1, -1);
  84210. vertices.push(1, -1);
  84211. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  84212. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  84213. };
  84214. /**
  84215. * Sets the main texture desired size which is the closest power of two
  84216. * of the engine canvas size.
  84217. */
  84218. EffectLayer.prototype._setMainTextureSize = function () {
  84219. if (this._effectLayerOptions.mainTextureFixedSize) {
  84220. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  84221. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  84222. }
  84223. else {
  84224. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  84225. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  84226. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  84227. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  84228. }
  84229. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  84230. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  84231. };
  84232. /**
  84233. * Creates the main texture for the effect layer.
  84234. */
  84235. EffectLayer.prototype._createMainTexture = function () {
  84236. var _this = this;
  84237. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  84238. width: this._mainTextureDesiredSize.width,
  84239. height: this._mainTextureDesiredSize.height
  84240. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  84241. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  84242. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84243. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84244. this._mainTexture.anisotropicFilteringLevel = 1;
  84245. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84246. this._mainTexture.renderParticles = false;
  84247. this._mainTexture.renderList = null;
  84248. this._mainTexture.ignoreCameraViewport = true;
  84249. // Custom render function
  84250. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  84251. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  84252. var index;
  84253. var engine = _this._scene.getEngine();
  84254. if (depthOnlySubMeshes.length) {
  84255. engine.setColorWrite(false);
  84256. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  84257. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  84258. }
  84259. engine.setColorWrite(true);
  84260. }
  84261. for (index = 0; index < opaqueSubMeshes.length; index++) {
  84262. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  84263. }
  84264. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  84265. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  84266. }
  84267. for (index = 0; index < transparentSubMeshes.length; index++) {
  84268. _this._renderSubMesh(transparentSubMeshes.data[index]);
  84269. }
  84270. };
  84271. this._mainTexture.onClearObservable.add(function (engine) {
  84272. engine.clear(_this.neutralColor, true, true, true);
  84273. });
  84274. };
  84275. /**
  84276. * Checks for the readiness of the element composing the layer.
  84277. * @param subMesh the mesh to check for
  84278. * @param useInstances specify wether or not to use instances to render the mesh
  84279. * @param emissiveTexture the associated emissive texture used to generate the glow
  84280. * @return true if ready otherwise, false
  84281. */
  84282. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  84283. var material = subMesh.getMaterial();
  84284. if (!material) {
  84285. return false;
  84286. }
  84287. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  84288. return false;
  84289. }
  84290. var defines = [];
  84291. var attribs = [BABYLON.VertexBuffer.PositionKind];
  84292. var mesh = subMesh.getMesh();
  84293. var uv1 = false;
  84294. var uv2 = false;
  84295. // Alpha test
  84296. if (material && material.needAlphaTesting()) {
  84297. var alphaTexture = material.getAlphaTestTexture();
  84298. if (alphaTexture) {
  84299. defines.push("#define ALPHATEST");
  84300. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  84301. alphaTexture.coordinatesIndex === 1) {
  84302. defines.push("#define DIFFUSEUV2");
  84303. uv2 = true;
  84304. }
  84305. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84306. defines.push("#define DIFFUSEUV1");
  84307. uv1 = true;
  84308. }
  84309. }
  84310. }
  84311. // Emissive
  84312. if (emissiveTexture) {
  84313. defines.push("#define EMISSIVE");
  84314. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  84315. emissiveTexture.coordinatesIndex === 1) {
  84316. defines.push("#define EMISSIVEUV2");
  84317. uv2 = true;
  84318. }
  84319. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84320. defines.push("#define EMISSIVEUV1");
  84321. uv1 = true;
  84322. }
  84323. }
  84324. if (uv1) {
  84325. attribs.push(BABYLON.VertexBuffer.UVKind);
  84326. defines.push("#define UV1");
  84327. }
  84328. if (uv2) {
  84329. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  84330. defines.push("#define UV2");
  84331. }
  84332. // Bones
  84333. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  84334. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  84335. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  84336. if (mesh.numBoneInfluencers > 4) {
  84337. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  84338. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  84339. }
  84340. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  84341. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  84342. }
  84343. else {
  84344. defines.push("#define NUM_BONE_INFLUENCERS 0");
  84345. }
  84346. // Instances
  84347. if (useInstances) {
  84348. defines.push("#define INSTANCES");
  84349. attribs.push("world0");
  84350. attribs.push("world1");
  84351. attribs.push("world2");
  84352. attribs.push("world3");
  84353. }
  84354. // Get correct effect
  84355. var join = defines.join("\n");
  84356. if (this._cachedDefines !== join) {
  84357. this._cachedDefines = join;
  84358. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  84359. }
  84360. return this._effectLayerMapGenerationEffect.isReady();
  84361. };
  84362. /**
  84363. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  84364. */
  84365. EffectLayer.prototype.render = function () {
  84366. var currentEffect = this._mergeEffect;
  84367. // Check
  84368. if (!currentEffect.isReady())
  84369. return;
  84370. for (var i = 0; i < this._postProcesses.length; i++) {
  84371. if (!this._postProcesses[i].isReady()) {
  84372. return;
  84373. }
  84374. }
  84375. var engine = this._scene.getEngine();
  84376. this.onBeforeComposeObservable.notifyObservers(this);
  84377. // Render
  84378. engine.enableEffect(currentEffect);
  84379. engine.setState(false);
  84380. // VBOs
  84381. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  84382. // Cache
  84383. var previousAlphaMode = engine.getAlphaMode();
  84384. // Go Blend.
  84385. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  84386. // Blends the map on the main canvas.
  84387. this._internalRender(currentEffect);
  84388. // Restore Alpha
  84389. engine.setAlphaMode(previousAlphaMode);
  84390. this.onAfterComposeObservable.notifyObservers(this);
  84391. // Handle size changes.
  84392. var size = this._mainTexture.getSize();
  84393. this._setMainTextureSize();
  84394. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  84395. // Recreate RTT and post processes on size change.
  84396. this.onSizeChangedObservable.notifyObservers(this);
  84397. this._disposeTextureAndPostProcesses();
  84398. this._createMainTexture();
  84399. this._createTextureAndPostProcesses();
  84400. }
  84401. };
  84402. /**
  84403. * Determine if a given mesh will be used in the current effect.
  84404. * @param mesh mesh to test
  84405. * @returns true if the mesh will be used
  84406. */
  84407. EffectLayer.prototype.hasMesh = function (mesh) {
  84408. return true;
  84409. };
  84410. /**
  84411. * Returns true if the layer contains information to display, otherwise false.
  84412. * @returns true if the glow layer should be rendered
  84413. */
  84414. EffectLayer.prototype.shouldRender = function () {
  84415. return this.isEnabled && this._shouldRender;
  84416. };
  84417. /**
  84418. * Returns true if the mesh should render, otherwise false.
  84419. * @param mesh The mesh to render
  84420. * @returns true if it should render otherwise false
  84421. */
  84422. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  84423. return true;
  84424. };
  84425. /**
  84426. * Returns true if the mesh should render, otherwise false.
  84427. * @param mesh The mesh to render
  84428. * @returns true if it should render otherwise false
  84429. */
  84430. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  84431. return true;
  84432. };
  84433. /**
  84434. * Renders the submesh passed in parameter to the generation map.
  84435. */
  84436. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  84437. var _this = this;
  84438. if (!this.shouldRender()) {
  84439. return;
  84440. }
  84441. var material = subMesh.getMaterial();
  84442. var mesh = subMesh.getRenderingMesh();
  84443. var scene = this._scene;
  84444. var engine = scene.getEngine();
  84445. if (!material) {
  84446. return;
  84447. }
  84448. // Do not block in blend mode.
  84449. if (material.needAlphaBlendingForMesh(mesh)) {
  84450. return;
  84451. }
  84452. // Culling
  84453. engine.setState(material.backFaceCulling);
  84454. // Managing instances
  84455. var batch = mesh._getInstancesRenderList(subMesh._id);
  84456. if (batch.mustReturn) {
  84457. return;
  84458. }
  84459. // Early Exit per mesh
  84460. if (!this._shouldRenderMesh(mesh)) {
  84461. return;
  84462. }
  84463. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  84464. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  84465. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  84466. engine.enableEffect(this._effectLayerMapGenerationEffect);
  84467. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  84468. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  84469. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  84470. // Alpha test
  84471. if (material && material.needAlphaTesting()) {
  84472. var alphaTexture = material.getAlphaTestTexture();
  84473. if (alphaTexture) {
  84474. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  84475. var textureMatrix = alphaTexture.getTextureMatrix();
  84476. if (textureMatrix) {
  84477. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  84478. }
  84479. }
  84480. }
  84481. // Glow emissive only
  84482. if (this._emissiveTextureAndColor.texture) {
  84483. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  84484. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  84485. }
  84486. // Bones
  84487. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  84488. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  84489. }
  84490. // Draw
  84491. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  84492. }
  84493. else {
  84494. // Need to reset refresh rate of the shadowMap
  84495. this._mainTexture.resetRefreshCounter();
  84496. }
  84497. };
  84498. /**
  84499. * Rebuild the required buffers.
  84500. * @ignore Internal use only.
  84501. */
  84502. EffectLayer.prototype._rebuild = function () {
  84503. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84504. if (vb) {
  84505. vb._rebuild();
  84506. }
  84507. this._generateIndexBuffer();
  84508. };
  84509. /**
  84510. * Dispose only the render target textures and post process.
  84511. */
  84512. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  84513. this._mainTexture.dispose();
  84514. for (var i = 0; i < this._postProcesses.length; i++) {
  84515. if (this._postProcesses[i]) {
  84516. this._postProcesses[i].dispose();
  84517. }
  84518. }
  84519. this._postProcesses = [];
  84520. for (var i = 0; i < this._textures.length; i++) {
  84521. if (this._textures[i]) {
  84522. this._textures[i].dispose();
  84523. }
  84524. }
  84525. this._textures = [];
  84526. };
  84527. /**
  84528. * Dispose the highlight layer and free resources.
  84529. */
  84530. EffectLayer.prototype.dispose = function () {
  84531. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84532. if (vertexBuffer) {
  84533. vertexBuffer.dispose();
  84534. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84535. }
  84536. if (this._indexBuffer) {
  84537. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84538. this._indexBuffer = null;
  84539. }
  84540. // Clean textures and post processes
  84541. this._disposeTextureAndPostProcesses();
  84542. // Remove from scene
  84543. var index = this._scene.effectLayers.indexOf(this, 0);
  84544. if (index > -1) {
  84545. this._scene.effectLayers.splice(index, 1);
  84546. }
  84547. // Callback
  84548. this.onDisposeObservable.notifyObservers(this);
  84549. this.onDisposeObservable.clear();
  84550. this.onBeforeRenderMainTextureObservable.clear();
  84551. this.onBeforeComposeObservable.clear();
  84552. this.onAfterComposeObservable.clear();
  84553. this.onSizeChangedObservable.clear();
  84554. };
  84555. return EffectLayer;
  84556. }());
  84557. BABYLON.EffectLayer = EffectLayer;
  84558. })(BABYLON || (BABYLON = {}));
  84559. //# sourceMappingURL=babylon.effectLayer.js.map
  84560. var BABYLON;
  84561. (function (BABYLON) {
  84562. /**
  84563. * Special Glow Blur post process only blurring the alpha channel
  84564. * It enforces keeping the most luminous color in the color channel.
  84565. */
  84566. var GlowBlurPostProcess = /** @class */ (function (_super) {
  84567. __extends(GlowBlurPostProcess, _super);
  84568. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  84569. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  84570. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  84571. _this.direction = direction;
  84572. _this.kernel = kernel;
  84573. _this.onApplyObservable.add(function (effect) {
  84574. effect.setFloat2("screenSize", _this.width, _this.height);
  84575. effect.setVector2("direction", _this.direction);
  84576. effect.setFloat("blurWidth", _this.kernel);
  84577. });
  84578. return _this;
  84579. }
  84580. return GlowBlurPostProcess;
  84581. }(BABYLON.PostProcess));
  84582. /**
  84583. * The highlight layer Helps adding a glow effect around a mesh.
  84584. *
  84585. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  84586. * glowy meshes to your scene.
  84587. *
  84588. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  84589. */
  84590. var HighlightLayer = /** @class */ (function (_super) {
  84591. __extends(HighlightLayer, _super);
  84592. /**
  84593. * Instantiates a new highlight Layer and references it to the scene..
  84594. * @param name The name of the layer
  84595. * @param scene The scene to use the layer in
  84596. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  84597. */
  84598. function HighlightLayer(name, scene, options) {
  84599. var _this = _super.call(this, name, scene) || this;
  84600. _this.name = name;
  84601. /**
  84602. * Specifies whether or not the inner glow is ACTIVE in the layer.
  84603. */
  84604. _this.innerGlow = true;
  84605. /**
  84606. * Specifies whether or not the outer glow is ACTIVE in the layer.
  84607. */
  84608. _this.outerGlow = true;
  84609. /**
  84610. * An event triggered when the highlight layer is being blurred.
  84611. */
  84612. _this.onBeforeBlurObservable = new BABYLON.Observable();
  84613. /**
  84614. * An event triggered when the highlight layer has been blurred.
  84615. */
  84616. _this.onAfterBlurObservable = new BABYLON.Observable();
  84617. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  84618. _this._meshes = {};
  84619. _this._excludedMeshes = {};
  84620. _this.neutralColor = HighlightLayer.NeutralColor;
  84621. // Warn on stencil
  84622. if (!_this._engine.isStencilEnable) {
  84623. 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 }");
  84624. }
  84625. // Adapt options
  84626. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  84627. // Initialize the layer
  84628. _this._init({
  84629. alphaBlendingMode: _this._options.alphaBlendingMode,
  84630. camera: _this._options.camera,
  84631. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  84632. mainTextureRatio: _this._options.mainTextureRatio
  84633. });
  84634. // Do not render as long as no meshes have been added
  84635. _this._shouldRender = false;
  84636. return _this;
  84637. }
  84638. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  84639. /**
  84640. * Gets the horizontal size of the blur.
  84641. */
  84642. get: function () {
  84643. return this._horizontalBlurPostprocess.kernel;
  84644. },
  84645. /**
  84646. * Specifies the horizontal size of the blur.
  84647. */
  84648. set: function (value) {
  84649. this._horizontalBlurPostprocess.kernel = value;
  84650. },
  84651. enumerable: true,
  84652. configurable: true
  84653. });
  84654. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  84655. /**
  84656. * Gets the vertical size of the blur.
  84657. */
  84658. get: function () {
  84659. return this._verticalBlurPostprocess.kernel;
  84660. },
  84661. /**
  84662. * Specifies the vertical size of the blur.
  84663. */
  84664. set: function (value) {
  84665. this._verticalBlurPostprocess.kernel = value;
  84666. },
  84667. enumerable: true,
  84668. configurable: true
  84669. });
  84670. /**
  84671. * Get the effect name of the layer.
  84672. * @return The effect name
  84673. */
  84674. HighlightLayer.prototype.getEffectName = function () {
  84675. return HighlightLayer.EffectName;
  84676. };
  84677. /**
  84678. * Create the merge effect. This is the shader use to blit the information back
  84679. * to the main canvas at the end of the scene rendering.
  84680. */
  84681. HighlightLayer.prototype._createMergeEffect = function () {
  84682. // Effect
  84683. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  84684. };
  84685. /**
  84686. * Creates the render target textures and post processes used in the highlight layer.
  84687. */
  84688. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  84689. var _this = this;
  84690. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  84691. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  84692. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  84693. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  84694. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  84695. width: blurTextureWidth,
  84696. height: blurTextureHeight
  84697. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84698. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84699. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84700. this._blurTexture.anisotropicFilteringLevel = 16;
  84701. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  84702. this._blurTexture.renderParticles = false;
  84703. this._blurTexture.ignoreCameraViewport = true;
  84704. this._textures = [this._blurTexture];
  84705. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  84706. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  84707. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  84708. effect.setTexture("textureSampler", _this._mainTexture);
  84709. });
  84710. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  84711. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  84712. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  84713. });
  84714. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  84715. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  84716. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  84717. });
  84718. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  84719. }
  84720. else {
  84721. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  84722. width: blurTextureWidth,
  84723. height: blurTextureHeight
  84724. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84725. this._horizontalBlurPostprocess.width = blurTextureWidth;
  84726. this._horizontalBlurPostprocess.height = blurTextureHeight;
  84727. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  84728. effect.setTexture("textureSampler", _this._mainTexture);
  84729. });
  84730. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  84731. width: blurTextureWidth,
  84732. height: blurTextureHeight
  84733. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84734. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  84735. }
  84736. this._mainTexture.onAfterUnbindObservable.add(function () {
  84737. _this.onBeforeBlurObservable.notifyObservers(_this);
  84738. var internalTexture = _this._blurTexture.getInternalTexture();
  84739. if (internalTexture) {
  84740. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  84741. }
  84742. _this.onAfterBlurObservable.notifyObservers(_this);
  84743. });
  84744. // Prevent autoClear.
  84745. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  84746. };
  84747. /**
  84748. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  84749. */
  84750. HighlightLayer.prototype.needStencil = function () {
  84751. return true;
  84752. };
  84753. /**
  84754. * Checks for the readiness of the element composing the layer.
  84755. * @param subMesh the mesh to check for
  84756. * @param useInstances specify wether or not to use instances to render the mesh
  84757. * @param emissiveTexture the associated emissive texture used to generate the glow
  84758. * @return true if ready otherwise, false
  84759. */
  84760. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  84761. var material = subMesh.getMaterial();
  84762. var mesh = subMesh.getRenderingMesh();
  84763. if (!material || !mesh || !this._meshes) {
  84764. return false;
  84765. }
  84766. var emissiveTexture = null;
  84767. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  84768. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  84769. emissiveTexture = material.emissiveTexture;
  84770. }
  84771. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  84772. };
  84773. /**
  84774. * Implementation specific of rendering the generating effect on the main canvas.
  84775. * @param effect The effect used to render through
  84776. */
  84777. HighlightLayer.prototype._internalRender = function (effect) {
  84778. // Texture
  84779. effect.setTexture("textureSampler", this._blurTexture);
  84780. // Cache
  84781. var engine = this._engine;
  84782. var previousStencilBuffer = engine.getStencilBuffer();
  84783. var previousStencilFunction = engine.getStencilFunction();
  84784. var previousStencilMask = engine.getStencilMask();
  84785. var previousStencilOperationPass = engine.getStencilOperationPass();
  84786. var previousStencilOperationFail = engine.getStencilOperationFail();
  84787. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  84788. var previousStencilReference = engine.getStencilFunctionReference();
  84789. // Stencil operations
  84790. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  84791. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  84792. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  84793. // Draw order
  84794. engine.setStencilMask(0x00);
  84795. engine.setStencilBuffer(true);
  84796. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  84797. // 2 passes inner outer
  84798. if (this.outerGlow) {
  84799. effect.setFloat("offset", 0);
  84800. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  84801. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84802. }
  84803. if (this.innerGlow) {
  84804. effect.setFloat("offset", 1);
  84805. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  84806. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84807. }
  84808. // Restore Cache
  84809. engine.setStencilFunction(previousStencilFunction);
  84810. engine.setStencilMask(previousStencilMask);
  84811. engine.setStencilBuffer(previousStencilBuffer);
  84812. engine.setStencilOperationPass(previousStencilOperationPass);
  84813. engine.setStencilOperationFail(previousStencilOperationFail);
  84814. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  84815. engine.setStencilFunctionReference(previousStencilReference);
  84816. };
  84817. /**
  84818. * Returns true if the layer contains information to display, otherwise false.
  84819. */
  84820. HighlightLayer.prototype.shouldRender = function () {
  84821. if (_super.prototype.shouldRender.call(this)) {
  84822. return this._meshes ? true : false;
  84823. }
  84824. return false;
  84825. };
  84826. /**
  84827. * Returns true if the mesh should render, otherwise false.
  84828. * @param mesh The mesh to render
  84829. * @returns true if it should render otherwise false
  84830. */
  84831. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  84832. // Excluded Mesh
  84833. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  84834. return false;
  84835. }
  84836. ;
  84837. return true;
  84838. };
  84839. /**
  84840. * Sets the required values for both the emissive texture and and the main color.
  84841. */
  84842. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  84843. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  84844. if (highlightLayerMesh) {
  84845. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  84846. }
  84847. else {
  84848. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  84849. }
  84850. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  84851. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  84852. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  84853. }
  84854. else {
  84855. this._emissiveTextureAndColor.texture = null;
  84856. }
  84857. };
  84858. /**
  84859. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  84860. * @param mesh The mesh to exclude from the highlight layer
  84861. */
  84862. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  84863. if (!this._excludedMeshes) {
  84864. return;
  84865. }
  84866. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  84867. if (!meshExcluded) {
  84868. this._excludedMeshes[mesh.uniqueId] = {
  84869. mesh: mesh,
  84870. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  84871. mesh.getEngine().setStencilBuffer(false);
  84872. }),
  84873. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  84874. mesh.getEngine().setStencilBuffer(true);
  84875. }),
  84876. };
  84877. }
  84878. };
  84879. /**
  84880. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  84881. * @param mesh The mesh to highlight
  84882. */
  84883. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  84884. if (!this._excludedMeshes) {
  84885. return;
  84886. }
  84887. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  84888. if (meshExcluded) {
  84889. if (meshExcluded.beforeRender) {
  84890. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  84891. }
  84892. if (meshExcluded.afterRender) {
  84893. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  84894. }
  84895. }
  84896. this._excludedMeshes[mesh.uniqueId] = null;
  84897. };
  84898. /**
  84899. * Determine if a given mesh will be highlighted by the current HighlightLayer
  84900. * @param mesh mesh to test
  84901. * @returns true if the mesh will be highlighted by the current HighlightLayer
  84902. */
  84903. HighlightLayer.prototype.hasMesh = function (mesh) {
  84904. if (!this._meshes) {
  84905. return false;
  84906. }
  84907. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  84908. };
  84909. /**
  84910. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  84911. * @param mesh The mesh to highlight
  84912. * @param color The color of the highlight
  84913. * @param glowEmissiveOnly Extract the glow from the emissive texture
  84914. */
  84915. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  84916. var _this = this;
  84917. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  84918. if (!this._meshes) {
  84919. return;
  84920. }
  84921. var meshHighlight = this._meshes[mesh.uniqueId];
  84922. if (meshHighlight) {
  84923. meshHighlight.color = color;
  84924. }
  84925. else {
  84926. this._meshes[mesh.uniqueId] = {
  84927. mesh: mesh,
  84928. color: color,
  84929. // Lambda required for capture due to Observable this context
  84930. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  84931. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  84932. _this._defaultStencilReference(mesh);
  84933. }
  84934. else {
  84935. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  84936. }
  84937. }),
  84938. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  84939. glowEmissiveOnly: glowEmissiveOnly
  84940. };
  84941. }
  84942. this._shouldRender = true;
  84943. };
  84944. /**
  84945. * Remove a mesh from the highlight layer in order to make it stop glowing.
  84946. * @param mesh The mesh to highlight
  84947. */
  84948. HighlightLayer.prototype.removeMesh = function (mesh) {
  84949. if (!this._meshes) {
  84950. return;
  84951. }
  84952. var meshHighlight = this._meshes[mesh.uniqueId];
  84953. if (meshHighlight) {
  84954. if (meshHighlight.observerHighlight) {
  84955. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  84956. }
  84957. if (meshHighlight.observerDefault) {
  84958. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  84959. }
  84960. delete this._meshes[mesh.uniqueId];
  84961. }
  84962. this._shouldRender = false;
  84963. for (var meshHighlightToCheck in this._meshes) {
  84964. if (this._meshes[meshHighlightToCheck]) {
  84965. this._shouldRender = true;
  84966. break;
  84967. }
  84968. }
  84969. };
  84970. /**
  84971. * Force the stencil to the normal expected value for none glowing parts
  84972. */
  84973. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  84974. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  84975. };
  84976. /**
  84977. * Free any resources and references associated to a mesh.
  84978. * Internal use
  84979. * @param mesh The mesh to free.
  84980. */
  84981. HighlightLayer.prototype._disposeMesh = function (mesh) {
  84982. this.removeMesh(mesh);
  84983. this.removeExcludedMesh(mesh);
  84984. };
  84985. /**
  84986. * Dispose the highlight layer and free resources.
  84987. */
  84988. HighlightLayer.prototype.dispose = function () {
  84989. if (this._meshes) {
  84990. // Clean mesh references
  84991. for (var id in this._meshes) {
  84992. var meshHighlight = this._meshes[id];
  84993. if (meshHighlight && meshHighlight.mesh) {
  84994. if (meshHighlight.observerHighlight) {
  84995. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  84996. }
  84997. if (meshHighlight.observerDefault) {
  84998. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  84999. }
  85000. }
  85001. }
  85002. this._meshes = null;
  85003. }
  85004. if (this._excludedMeshes) {
  85005. for (var id in this._excludedMeshes) {
  85006. var meshHighlight = this._excludedMeshes[id];
  85007. if (meshHighlight) {
  85008. if (meshHighlight.beforeRender) {
  85009. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  85010. }
  85011. if (meshHighlight.afterRender) {
  85012. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  85013. }
  85014. }
  85015. }
  85016. this._excludedMeshes = null;
  85017. }
  85018. _super.prototype.dispose.call(this);
  85019. };
  85020. /**
  85021. * Effect Name of the highlight layer.
  85022. */
  85023. HighlightLayer.EffectName = "HighlightLayer";
  85024. /**
  85025. * The neutral color used during the preparation of the glow effect.
  85026. * This is black by default as the blend operation is a blend operation.
  85027. */
  85028. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  85029. /**
  85030. * Stencil value used for glowing meshes.
  85031. */
  85032. HighlightLayer.GlowingMeshStencilReference = 0x02;
  85033. /**
  85034. * Stencil value used for the other meshes in the scene.
  85035. */
  85036. HighlightLayer.NormalMeshStencilReference = 0x01;
  85037. return HighlightLayer;
  85038. }(BABYLON.EffectLayer));
  85039. BABYLON.HighlightLayer = HighlightLayer;
  85040. })(BABYLON || (BABYLON = {}));
  85041. //# sourceMappingURL=babylon.highlightLayer.js.map
  85042. var BABYLON;
  85043. (function (BABYLON) {
  85044. /**
  85045. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  85046. *
  85047. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  85048. * glowy meshes to your scene.
  85049. *
  85050. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  85051. */
  85052. var GlowLayer = /** @class */ (function (_super) {
  85053. __extends(GlowLayer, _super);
  85054. /**
  85055. * Instantiates a new glow Layer and references it to the scene.
  85056. * @param name The name of the layer
  85057. * @param scene The scene to use the layer in
  85058. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  85059. */
  85060. function GlowLayer(name, scene, options) {
  85061. var _this = _super.call(this, name, scene) || this;
  85062. _this.name = name;
  85063. _this._intensity = 1.0;
  85064. _this._includedOnlyMeshes = [];
  85065. _this._excludedMeshes = [];
  85066. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  85067. // Adapt options
  85068. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  85069. // Initialize the layer
  85070. _this._init({
  85071. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  85072. camera: _this._options.camera,
  85073. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  85074. mainTextureRatio: _this._options.mainTextureRatio
  85075. });
  85076. return _this;
  85077. }
  85078. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  85079. /**
  85080. * Gets the kernel size of the blur.
  85081. */
  85082. get: function () {
  85083. return this._horizontalBlurPostprocess1.kernel;
  85084. },
  85085. /**
  85086. * Sets the kernel size of the blur.
  85087. */
  85088. set: function (value) {
  85089. this._horizontalBlurPostprocess1.kernel = value;
  85090. this._verticalBlurPostprocess1.kernel = value;
  85091. this._horizontalBlurPostprocess2.kernel = value;
  85092. this._verticalBlurPostprocess2.kernel = value;
  85093. },
  85094. enumerable: true,
  85095. configurable: true
  85096. });
  85097. Object.defineProperty(GlowLayer.prototype, "intensity", {
  85098. /**
  85099. * Gets the glow intensity.
  85100. */
  85101. get: function () {
  85102. return this._intensity;
  85103. },
  85104. /**
  85105. * Sets the glow intensity.
  85106. */
  85107. set: function (value) {
  85108. this._intensity = value;
  85109. },
  85110. enumerable: true,
  85111. configurable: true
  85112. });
  85113. /**
  85114. * Get the effect name of the layer.
  85115. * @return The effect name
  85116. */
  85117. GlowLayer.prototype.getEffectName = function () {
  85118. return GlowLayer.EffectName;
  85119. };
  85120. /**
  85121. * Create the merge effect. This is the shader use to blit the information back
  85122. * to the main canvas at the end of the scene rendering.
  85123. */
  85124. GlowLayer.prototype._createMergeEffect = function () {
  85125. // Effect
  85126. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  85127. };
  85128. /**
  85129. * Creates the render target textures and post processes used in the glow layer.
  85130. */
  85131. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  85132. var _this = this;
  85133. var blurTextureWidth = this._mainTextureDesiredSize.width;
  85134. var blurTextureHeight = this._mainTextureDesiredSize.height;
  85135. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  85136. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  85137. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  85138. width: blurTextureWidth,
  85139. height: blurTextureHeight
  85140. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85141. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85142. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85143. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85144. this._blurTexture1.renderParticles = false;
  85145. this._blurTexture1.ignoreCameraViewport = true;
  85146. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  85147. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  85148. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  85149. width: blurTextureWidth2,
  85150. height: blurTextureHeight2
  85151. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85152. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85153. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85154. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85155. this._blurTexture2.renderParticles = false;
  85156. this._blurTexture2.ignoreCameraViewport = true;
  85157. this._textures = [this._blurTexture1, this._blurTexture2];
  85158. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  85159. width: blurTextureWidth,
  85160. height: blurTextureHeight
  85161. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85162. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  85163. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  85164. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  85165. effect.setTexture("textureSampler", _this._mainTexture);
  85166. });
  85167. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  85168. width: blurTextureWidth,
  85169. height: blurTextureHeight
  85170. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85171. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  85172. width: blurTextureWidth2,
  85173. height: blurTextureHeight2
  85174. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85175. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  85176. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  85177. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  85178. effect.setTexture("textureSampler", _this._blurTexture1);
  85179. });
  85180. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  85181. width: blurTextureWidth2,
  85182. height: blurTextureHeight2
  85183. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85184. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  85185. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  85186. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  85187. this._mainTexture.samples = this._options.mainTextureSamples;
  85188. this._mainTexture.onAfterUnbindObservable.add(function () {
  85189. var internalTexture = _this._blurTexture1.getInternalTexture();
  85190. if (internalTexture) {
  85191. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  85192. internalTexture = _this._blurTexture2.getInternalTexture();
  85193. if (internalTexture) {
  85194. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  85195. }
  85196. }
  85197. });
  85198. // Prevent autoClear.
  85199. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  85200. };
  85201. /**
  85202. * Checks for the readiness of the element composing the layer.
  85203. * @param subMesh the mesh to check for
  85204. * @param useInstances specify wether or not to use instances to render the mesh
  85205. * @param emissiveTexture the associated emissive texture used to generate the glow
  85206. * @return true if ready otherwise, false
  85207. */
  85208. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  85209. var material = subMesh.getMaterial();
  85210. var mesh = subMesh.getRenderingMesh();
  85211. if (!material || !mesh) {
  85212. return false;
  85213. }
  85214. var emissiveTexture = material.emissiveTexture;
  85215. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  85216. };
  85217. /**
  85218. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  85219. */
  85220. GlowLayer.prototype.needStencil = function () {
  85221. return false;
  85222. };
  85223. /**
  85224. * Implementation specific of rendering the generating effect on the main canvas.
  85225. * @param effect The effect used to render through
  85226. */
  85227. GlowLayer.prototype._internalRender = function (effect) {
  85228. // Texture
  85229. effect.setTexture("textureSampler", this._blurTexture1);
  85230. effect.setTexture("textureSampler2", this._blurTexture2);
  85231. effect.setFloat("offset", this._intensity);
  85232. // Cache
  85233. var engine = this._engine;
  85234. var previousStencilBuffer = engine.getStencilBuffer();
  85235. // Draw order
  85236. engine.setStencilBuffer(false);
  85237. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85238. // Draw order
  85239. engine.setStencilBuffer(previousStencilBuffer);
  85240. };
  85241. /**
  85242. * Sets the required values for both the emissive texture and and the main color.
  85243. */
  85244. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  85245. var textureLevel = 1.0;
  85246. if (this.customEmissiveTextureSelector) {
  85247. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  85248. }
  85249. else {
  85250. if (material) {
  85251. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  85252. if (this._emissiveTextureAndColor.texture) {
  85253. textureLevel = this._emissiveTextureAndColor.texture.level;
  85254. }
  85255. }
  85256. else {
  85257. this._emissiveTextureAndColor.texture = null;
  85258. }
  85259. }
  85260. if (this.customEmissiveColorSelector) {
  85261. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  85262. }
  85263. else {
  85264. if (material.emissiveColor) {
  85265. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  85266. }
  85267. else {
  85268. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  85269. }
  85270. }
  85271. };
  85272. /**
  85273. * Returns true if the mesh should render, otherwise false.
  85274. * @param mesh The mesh to render
  85275. * @returns true if it should render otherwise false
  85276. */
  85277. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  85278. return this.hasMesh(mesh);
  85279. };
  85280. /**
  85281. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  85282. * @param mesh The mesh to exclude from the glow layer
  85283. */
  85284. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  85285. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  85286. this._excludedMeshes.push(mesh.uniqueId);
  85287. }
  85288. };
  85289. /**
  85290. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  85291. * @param mesh The mesh to remove
  85292. */
  85293. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  85294. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  85295. if (index !== -1) {
  85296. this._excludedMeshes.splice(index, 1);
  85297. }
  85298. };
  85299. /**
  85300. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  85301. * @param mesh The mesh to include in the glow layer
  85302. */
  85303. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  85304. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  85305. this._includedOnlyMeshes.push(mesh.uniqueId);
  85306. }
  85307. };
  85308. /**
  85309. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  85310. * @param mesh The mesh to remove
  85311. */
  85312. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  85313. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  85314. if (index !== -1) {
  85315. this._includedOnlyMeshes.splice(index, 1);
  85316. }
  85317. };
  85318. /**
  85319. * Determine if a given mesh will be used in the glow layer
  85320. * @param mesh The mesh to test
  85321. * @returns true if the mesh will be highlighted by the current glow layer
  85322. */
  85323. GlowLayer.prototype.hasMesh = function (mesh) {
  85324. // Included Mesh
  85325. if (this._includedOnlyMeshes.length) {
  85326. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  85327. }
  85328. ;
  85329. // Excluded Mesh
  85330. if (this._excludedMeshes.length) {
  85331. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  85332. }
  85333. ;
  85334. return true;
  85335. };
  85336. /**
  85337. * Free any resources and references associated to a mesh.
  85338. * Internal use
  85339. * @param mesh The mesh to free.
  85340. */
  85341. GlowLayer.prototype._disposeMesh = function (mesh) {
  85342. this.removeIncludedOnlyMesh(mesh);
  85343. this.removeExcludedMesh(mesh);
  85344. };
  85345. /**
  85346. * Effect Name of the layer.
  85347. */
  85348. GlowLayer.EffectName = "GlowLayer";
  85349. /**
  85350. * The default blur kernel size used for the glow.
  85351. */
  85352. GlowLayer.DefaultBlurKernelSize = 32;
  85353. /**
  85354. * The default texture size ratio used for the glow.
  85355. */
  85356. GlowLayer.DefaultTextureRatio = 0.5;
  85357. return GlowLayer;
  85358. }(BABYLON.EffectLayer));
  85359. BABYLON.GlowLayer = GlowLayer;
  85360. })(BABYLON || (BABYLON = {}));
  85361. //# sourceMappingURL=babylon.glowLayer.js.map
  85362. var BABYLON;
  85363. (function (BABYLON) {
  85364. /**
  85365. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  85366. */
  85367. var AssetTaskState;
  85368. (function (AssetTaskState) {
  85369. /**
  85370. * Initialization
  85371. */
  85372. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  85373. /**
  85374. * Running
  85375. */
  85376. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  85377. /**
  85378. * Done
  85379. */
  85380. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  85381. /**
  85382. * Error
  85383. */
  85384. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  85385. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  85386. /**
  85387. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  85388. */
  85389. var AbstractAssetTask = /** @class */ (function () {
  85390. /**
  85391. * Creates a new {BABYLON.AssetsManager}
  85392. * @param name defines the name of the task
  85393. */
  85394. function AbstractAssetTask(
  85395. /**
  85396. * Task name
  85397. */ name) {
  85398. this.name = name;
  85399. this._isCompleted = false;
  85400. this._taskState = AssetTaskState.INIT;
  85401. }
  85402. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  85403. /**
  85404. * Get if the task is completed
  85405. */
  85406. get: function () {
  85407. return this._isCompleted;
  85408. },
  85409. enumerable: true,
  85410. configurable: true
  85411. });
  85412. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  85413. /**
  85414. * Gets the current state of the task
  85415. */
  85416. get: function () {
  85417. return this._taskState;
  85418. },
  85419. enumerable: true,
  85420. configurable: true
  85421. });
  85422. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  85423. /**
  85424. * Gets the current error object (if task is in error)
  85425. */
  85426. get: function () {
  85427. return this._errorObject;
  85428. },
  85429. enumerable: true,
  85430. configurable: true
  85431. });
  85432. /**
  85433. * Internal only
  85434. * @ignore
  85435. */
  85436. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  85437. if (this._errorObject) {
  85438. return;
  85439. }
  85440. this._errorObject = {
  85441. message: message,
  85442. exception: exception
  85443. };
  85444. };
  85445. /**
  85446. * Execute the current task
  85447. * @param scene defines the scene where you want your assets to be loaded
  85448. * @param onSuccess is a callback called when the task is successfully executed
  85449. * @param onError is a callback called if an error occurs
  85450. */
  85451. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  85452. var _this = this;
  85453. this._taskState = AssetTaskState.RUNNING;
  85454. this.runTask(scene, function () {
  85455. _this.onDoneCallback(onSuccess, onError);
  85456. }, function (msg, exception) {
  85457. _this.onErrorCallback(onError, msg, exception);
  85458. });
  85459. };
  85460. /**
  85461. * Execute the current task
  85462. * @param scene defines the scene where you want your assets to be loaded
  85463. * @param onSuccess is a callback called when the task is successfully executed
  85464. * @param onError is a callback called if an error occurs
  85465. */
  85466. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85467. throw new Error("runTask is not implemented");
  85468. };
  85469. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  85470. this._taskState = AssetTaskState.ERROR;
  85471. this._errorObject = {
  85472. message: message,
  85473. exception: exception
  85474. };
  85475. if (this.onError) {
  85476. this.onError(this, message, exception);
  85477. }
  85478. onError();
  85479. };
  85480. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  85481. try {
  85482. this._taskState = AssetTaskState.DONE;
  85483. this._isCompleted = true;
  85484. if (this.onSuccess) {
  85485. this.onSuccess(this);
  85486. }
  85487. onSuccess();
  85488. }
  85489. catch (e) {
  85490. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  85491. }
  85492. };
  85493. return AbstractAssetTask;
  85494. }());
  85495. BABYLON.AbstractAssetTask = AbstractAssetTask;
  85496. /**
  85497. * Class used to share progress information about assets loading
  85498. */
  85499. var AssetsProgressEvent = /** @class */ (function () {
  85500. /**
  85501. * Creates a {BABYLON.AssetsProgressEvent}
  85502. * @param remainingCount defines the number of remaining tasks to process
  85503. * @param totalCount defines the total number of tasks
  85504. * @param task defines the task that was just processed
  85505. */
  85506. function AssetsProgressEvent(remainingCount, totalCount, task) {
  85507. this.remainingCount = remainingCount;
  85508. this.totalCount = totalCount;
  85509. this.task = task;
  85510. }
  85511. return AssetsProgressEvent;
  85512. }());
  85513. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  85514. /**
  85515. * Define a task used by {BABYLON.AssetsManager} to load meshes
  85516. */
  85517. var MeshAssetTask = /** @class */ (function (_super) {
  85518. __extends(MeshAssetTask, _super);
  85519. /**
  85520. * Creates a new {BABYLON.MeshAssetTask}
  85521. * @param name defines the name of the task
  85522. * @param meshesNames defines the list of mesh's names you want to load
  85523. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  85524. * @param sceneFilename defines the filename of the scene to load from
  85525. */
  85526. function MeshAssetTask(
  85527. /**
  85528. * Defines the name of the task
  85529. */
  85530. name,
  85531. /**
  85532. * Defines the list of mesh's names you want to load
  85533. */
  85534. meshesNames,
  85535. /**
  85536. * Defines the root url to use as a base to load your meshes and associated resources
  85537. */
  85538. rootUrl,
  85539. /**
  85540. * Defines the filename of the scene to load from
  85541. */
  85542. sceneFilename) {
  85543. var _this = _super.call(this, name) || this;
  85544. _this.name = name;
  85545. _this.meshesNames = meshesNames;
  85546. _this.rootUrl = rootUrl;
  85547. _this.sceneFilename = sceneFilename;
  85548. return _this;
  85549. }
  85550. /**
  85551. * Execute the current task
  85552. * @param scene defines the scene where you want your assets to be loaded
  85553. * @param onSuccess is a callback called when the task is successfully executed
  85554. * @param onError is a callback called if an error occurs
  85555. */
  85556. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85557. var _this = this;
  85558. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  85559. _this.loadedMeshes = meshes;
  85560. _this.loadedParticleSystems = particleSystems;
  85561. _this.loadedSkeletons = skeletons;
  85562. onSuccess();
  85563. }, null, function (scene, message, exception) {
  85564. onError(message, exception);
  85565. });
  85566. };
  85567. return MeshAssetTask;
  85568. }(AbstractAssetTask));
  85569. BABYLON.MeshAssetTask = MeshAssetTask;
  85570. /**
  85571. * Define a task used by {BABYLON.AssetsManager} to load text content
  85572. */
  85573. var TextFileAssetTask = /** @class */ (function (_super) {
  85574. __extends(TextFileAssetTask, _super);
  85575. /**
  85576. * Creates a new TextFileAssetTask object
  85577. * @param name defines the name of the task
  85578. * @param url defines the location of the file to load
  85579. */
  85580. function TextFileAssetTask(
  85581. /**
  85582. * Defines the name of the task
  85583. */
  85584. name,
  85585. /**
  85586. * Defines the location of the file to load
  85587. */
  85588. url) {
  85589. var _this = _super.call(this, name) || this;
  85590. _this.name = name;
  85591. _this.url = url;
  85592. return _this;
  85593. }
  85594. /**
  85595. * Execute the current task
  85596. * @param scene defines the scene where you want your assets to be loaded
  85597. * @param onSuccess is a callback called when the task is successfully executed
  85598. * @param onError is a callback called if an error occurs
  85599. */
  85600. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85601. var _this = this;
  85602. scene._loadFile(this.url, function (data) {
  85603. _this.text = data;
  85604. onSuccess();
  85605. }, undefined, false, false, function (request, exception) {
  85606. if (request) {
  85607. onError(request.status + " " + request.statusText, exception);
  85608. }
  85609. });
  85610. };
  85611. return TextFileAssetTask;
  85612. }(AbstractAssetTask));
  85613. BABYLON.TextFileAssetTask = TextFileAssetTask;
  85614. /**
  85615. * Define a task used by {BABYLON.AssetsManager} to load binary data
  85616. */
  85617. var BinaryFileAssetTask = /** @class */ (function (_super) {
  85618. __extends(BinaryFileAssetTask, _super);
  85619. /**
  85620. * Creates a new BinaryFileAssetTask object
  85621. * @param name defines the name of the new task
  85622. * @param url defines the location of the file to load
  85623. */
  85624. function BinaryFileAssetTask(
  85625. /**
  85626. * Defines the name of the task
  85627. */
  85628. name,
  85629. /**
  85630. * Defines the location of the file to load
  85631. */
  85632. url) {
  85633. var _this = _super.call(this, name) || this;
  85634. _this.name = name;
  85635. _this.url = url;
  85636. return _this;
  85637. }
  85638. /**
  85639. * Execute the current task
  85640. * @param scene defines the scene where you want your assets to be loaded
  85641. * @param onSuccess is a callback called when the task is successfully executed
  85642. * @param onError is a callback called if an error occurs
  85643. */
  85644. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85645. var _this = this;
  85646. scene._loadFile(this.url, function (data) {
  85647. _this.data = data;
  85648. onSuccess();
  85649. }, undefined, true, true, function (request, exception) {
  85650. if (request) {
  85651. onError(request.status + " " + request.statusText, exception);
  85652. }
  85653. });
  85654. };
  85655. return BinaryFileAssetTask;
  85656. }(AbstractAssetTask));
  85657. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  85658. /**
  85659. * Define a task used by {BABYLON.AssetsManager} to load images
  85660. */
  85661. var ImageAssetTask = /** @class */ (function (_super) {
  85662. __extends(ImageAssetTask, _super);
  85663. /**
  85664. * Creates a new ImageAssetTask
  85665. * @param name defines the name of the task
  85666. * @param url defines the location of the image to load
  85667. */
  85668. function ImageAssetTask(
  85669. /**
  85670. * Defines the name of the task
  85671. */
  85672. name,
  85673. /**
  85674. * Defines the location of the image to load
  85675. */
  85676. url) {
  85677. var _this = _super.call(this, name) || this;
  85678. _this.name = name;
  85679. _this.url = url;
  85680. return _this;
  85681. }
  85682. /**
  85683. * Execute the current task
  85684. * @param scene defines the scene where you want your assets to be loaded
  85685. * @param onSuccess is a callback called when the task is successfully executed
  85686. * @param onError is a callback called if an error occurs
  85687. */
  85688. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85689. var _this = this;
  85690. var img = new Image();
  85691. BABYLON.Tools.SetCorsBehavior(this.url, img);
  85692. img.onload = function () {
  85693. _this.image = img;
  85694. onSuccess();
  85695. };
  85696. img.onerror = function (err) {
  85697. onError("Error loading image", err);
  85698. };
  85699. img.src = this.url;
  85700. };
  85701. return ImageAssetTask;
  85702. }(AbstractAssetTask));
  85703. BABYLON.ImageAssetTask = ImageAssetTask;
  85704. /**
  85705. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  85706. */
  85707. var TextureAssetTask = /** @class */ (function (_super) {
  85708. __extends(TextureAssetTask, _super);
  85709. /**
  85710. * Creates a new TextureAssetTask object
  85711. * @param name defines the name of the task
  85712. * @param url defines the location of the file to load
  85713. * @param noMipmap defines if mipmap should not be generated (default is false)
  85714. * @param invertY defines if texture must be inverted on Y axis (default is false)
  85715. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  85716. */
  85717. function TextureAssetTask(
  85718. /**
  85719. * Defines the name of the task
  85720. */
  85721. name,
  85722. /**
  85723. * Defines the location of the file to load
  85724. */
  85725. url,
  85726. /**
  85727. * Defines if mipmap should not be generated (default is false)
  85728. */
  85729. noMipmap,
  85730. /**
  85731. * Defines if texture must be inverted on Y axis (default is false)
  85732. */
  85733. invertY,
  85734. /**
  85735. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  85736. */
  85737. samplingMode) {
  85738. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  85739. var _this = _super.call(this, name) || this;
  85740. _this.name = name;
  85741. _this.url = url;
  85742. _this.noMipmap = noMipmap;
  85743. _this.invertY = invertY;
  85744. _this.samplingMode = samplingMode;
  85745. return _this;
  85746. }
  85747. /**
  85748. * Execute the current task
  85749. * @param scene defines the scene where you want your assets to be loaded
  85750. * @param onSuccess is a callback called when the task is successfully executed
  85751. * @param onError is a callback called if an error occurs
  85752. */
  85753. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85754. var onload = function () {
  85755. onSuccess();
  85756. };
  85757. var onerror = function (message, exception) {
  85758. onError(message, exception);
  85759. };
  85760. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  85761. };
  85762. return TextureAssetTask;
  85763. }(AbstractAssetTask));
  85764. BABYLON.TextureAssetTask = TextureAssetTask;
  85765. /**
  85766. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  85767. */
  85768. var CubeTextureAssetTask = /** @class */ (function (_super) {
  85769. __extends(CubeTextureAssetTask, _super);
  85770. /**
  85771. * Creates a new CubeTextureAssetTask
  85772. * @param name defines the name of the task
  85773. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  85774. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  85775. * @param noMipmap defines if mipmaps should not be generated (default is false)
  85776. * @param files defines the explicit list of files (undefined by default)
  85777. */
  85778. function CubeTextureAssetTask(
  85779. /**
  85780. * Defines the name of the task
  85781. */
  85782. name,
  85783. /**
  85784. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  85785. */
  85786. url,
  85787. /**
  85788. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  85789. */
  85790. extensions,
  85791. /**
  85792. * Defines if mipmaps should not be generated (default is false)
  85793. */
  85794. noMipmap,
  85795. /**
  85796. * Defines the explicit list of files (undefined by default)
  85797. */
  85798. files) {
  85799. var _this = _super.call(this, name) || this;
  85800. _this.name = name;
  85801. _this.url = url;
  85802. _this.extensions = extensions;
  85803. _this.noMipmap = noMipmap;
  85804. _this.files = files;
  85805. return _this;
  85806. }
  85807. /**
  85808. * Execute the current task
  85809. * @param scene defines the scene where you want your assets to be loaded
  85810. * @param onSuccess is a callback called when the task is successfully executed
  85811. * @param onError is a callback called if an error occurs
  85812. */
  85813. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85814. var onload = function () {
  85815. onSuccess();
  85816. };
  85817. var onerror = function (message, exception) {
  85818. onError(message, exception);
  85819. };
  85820. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  85821. };
  85822. return CubeTextureAssetTask;
  85823. }(AbstractAssetTask));
  85824. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  85825. /**
  85826. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  85827. */
  85828. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  85829. __extends(HDRCubeTextureAssetTask, _super);
  85830. /**
  85831. * Creates a new HDRCubeTextureAssetTask object
  85832. * @param name defines the name of the task
  85833. * @param url defines the location of the file to load
  85834. * @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.
  85835. * @param noMipmap defines if mipmaps should not be generated (default is false)
  85836. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  85837. * @param useInGammaSpace 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)
  85838. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  85839. */
  85840. function HDRCubeTextureAssetTask(
  85841. /**
  85842. * Defines the name of the task
  85843. */
  85844. name,
  85845. /**
  85846. * Defines the location of the file to load
  85847. */
  85848. url,
  85849. /**
  85850. * 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.
  85851. */
  85852. size,
  85853. /**
  85854. * Defines if mipmaps should not be generated (default is false)
  85855. */
  85856. noMipmap,
  85857. /**
  85858. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  85859. */
  85860. generateHarmonics,
  85861. /**
  85862. * 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)
  85863. */
  85864. useInGammaSpace,
  85865. /**
  85866. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  85867. */
  85868. usePMREMGenerator) {
  85869. if (noMipmap === void 0) { noMipmap = false; }
  85870. if (generateHarmonics === void 0) { generateHarmonics = true; }
  85871. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  85872. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  85873. var _this = _super.call(this, name) || this;
  85874. _this.name = name;
  85875. _this.url = url;
  85876. _this.size = size;
  85877. _this.noMipmap = noMipmap;
  85878. _this.generateHarmonics = generateHarmonics;
  85879. _this.useInGammaSpace = useInGammaSpace;
  85880. _this.usePMREMGenerator = usePMREMGenerator;
  85881. return _this;
  85882. }
  85883. /**
  85884. * Execute the current task
  85885. * @param scene defines the scene where you want your assets to be loaded
  85886. * @param onSuccess is a callback called when the task is successfully executed
  85887. * @param onError is a callback called if an error occurs
  85888. */
  85889. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  85890. var onload = function () {
  85891. onSuccess();
  85892. };
  85893. var onerror = function (message, exception) {
  85894. onError(message, exception);
  85895. };
  85896. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  85897. };
  85898. return HDRCubeTextureAssetTask;
  85899. }(AbstractAssetTask));
  85900. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  85901. /**
  85902. * This class can be used to easily import assets into a scene
  85903. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  85904. */
  85905. var AssetsManager = /** @class */ (function () {
  85906. /**
  85907. * Creates a new AssetsManager
  85908. * @param scene defines the scene to work on
  85909. */
  85910. function AssetsManager(scene) {
  85911. this._isLoading = false;
  85912. this._tasks = new Array();
  85913. this._waitingTasksCount = 0;
  85914. this._totalTasksCount = 0;
  85915. /**
  85916. * Observable called when all tasks are processed
  85917. */
  85918. this.onTaskSuccessObservable = new BABYLON.Observable();
  85919. /**
  85920. * Observable called when a task had an error
  85921. */
  85922. this.onTaskErrorObservable = new BABYLON.Observable();
  85923. /**
  85924. * Observable called when a task is successful
  85925. */
  85926. this.onTasksDoneObservable = new BABYLON.Observable();
  85927. /**
  85928. * Observable called when a task is done (whatever the result is)
  85929. */
  85930. this.onProgressObservable = new BABYLON.Observable();
  85931. /**
  85932. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  85933. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  85934. */
  85935. this.useDefaultLoadingScreen = true;
  85936. this._scene = scene;
  85937. }
  85938. /**
  85939. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  85940. * @param taskName defines the name of the new task
  85941. * @param meshesNames defines the name of meshes to load
  85942. * @param rootUrl defines the root url to use to locate files
  85943. * @param sceneFilename defines the filename of the scene file
  85944. * @returns a new {BABYLON.MeshAssetTask} object
  85945. */
  85946. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  85947. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  85948. this._tasks.push(task);
  85949. return task;
  85950. };
  85951. /**
  85952. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  85953. * @param taskName defines the name of the new task
  85954. * @param url defines the url of the file to load
  85955. * @returns a new {BABYLON.TextFileAssetTask} object
  85956. */
  85957. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  85958. var task = new TextFileAssetTask(taskName, url);
  85959. this._tasks.push(task);
  85960. return task;
  85961. };
  85962. /**
  85963. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  85964. * @param taskName defines the name of the new task
  85965. * @param url defines the url of the file to load
  85966. * @returns a new {BABYLON.BinaryFileAssetTask} object
  85967. */
  85968. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  85969. var task = new BinaryFileAssetTask(taskName, url);
  85970. this._tasks.push(task);
  85971. return task;
  85972. };
  85973. /**
  85974. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  85975. * @param taskName defines the name of the new task
  85976. * @param url defines the url of the file to load
  85977. * @returns a new {BABYLON.ImageAssetTask} object
  85978. */
  85979. AssetsManager.prototype.addImageTask = function (taskName, url) {
  85980. var task = new ImageAssetTask(taskName, url);
  85981. this._tasks.push(task);
  85982. return task;
  85983. };
  85984. /**
  85985. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  85986. * @param taskName defines the name of the new task
  85987. * @param url defines the url of the file to load
  85988. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  85989. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  85990. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  85991. * @returns a new {BABYLON.TextureAssetTask} object
  85992. */
  85993. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  85994. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  85995. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  85996. this._tasks.push(task);
  85997. return task;
  85998. };
  85999. /**
  86000. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  86001. * @param taskName defines the name of the new task
  86002. * @param url defines the url of the file to load
  86003. * @param extensions defines the extension to use to load the cube map (can be null)
  86004. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  86005. * @param files defines the list of files to load (can be null)
  86006. * @returns a new {BABYLON.CubeTextureAssetTask} object
  86007. */
  86008. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  86009. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  86010. this._tasks.push(task);
  86011. return task;
  86012. };
  86013. /**
  86014. *
  86015. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  86016. * @param taskName defines the name of the new task
  86017. * @param url defines the url of the file to load
  86018. * @param size defines the size you want for the cubemap (can be null)
  86019. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  86020. * @param generateHarmonics defines if you want to automatically generate (true by default)
  86021. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  86022. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  86023. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  86024. */
  86025. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  86026. if (noMipmap === void 0) { noMipmap = false; }
  86027. if (generateHarmonics === void 0) { generateHarmonics = true; }
  86028. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  86029. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  86030. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  86031. this._tasks.push(task);
  86032. return task;
  86033. };
  86034. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  86035. var _this = this;
  86036. this._waitingTasksCount--;
  86037. try {
  86038. if (task.taskState === AssetTaskState.DONE) {
  86039. // Let's remove successfull tasks
  86040. BABYLON.Tools.SetImmediate(function () {
  86041. var index = _this._tasks.indexOf(task);
  86042. if (index > -1) {
  86043. _this._tasks.splice(index, 1);
  86044. }
  86045. });
  86046. }
  86047. if (this.onProgress) {
  86048. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  86049. }
  86050. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  86051. }
  86052. catch (e) {
  86053. BABYLON.Tools.Error("Error running progress callbacks.");
  86054. console.log(e);
  86055. }
  86056. if (this._waitingTasksCount === 0) {
  86057. try {
  86058. if (this.onFinish) {
  86059. this.onFinish(this._tasks);
  86060. }
  86061. this.onTasksDoneObservable.notifyObservers(this._tasks);
  86062. }
  86063. catch (e) {
  86064. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  86065. console.log(e);
  86066. }
  86067. this._isLoading = false;
  86068. this._scene.getEngine().hideLoadingUI();
  86069. }
  86070. };
  86071. AssetsManager.prototype._runTask = function (task) {
  86072. var _this = this;
  86073. var done = function () {
  86074. try {
  86075. if (_this.onTaskSuccess) {
  86076. _this.onTaskSuccess(task);
  86077. }
  86078. _this.onTaskSuccessObservable.notifyObservers(task);
  86079. _this._decreaseWaitingTasksCount(task);
  86080. }
  86081. catch (e) {
  86082. error("Error executing task success callbacks", e);
  86083. }
  86084. };
  86085. var error = function (message, exception) {
  86086. task._setErrorObject(message, exception);
  86087. if (_this.onTaskError) {
  86088. _this.onTaskError(task);
  86089. }
  86090. _this.onTaskErrorObservable.notifyObservers(task);
  86091. _this._decreaseWaitingTasksCount(task);
  86092. };
  86093. task.run(this._scene, done, error);
  86094. };
  86095. /**
  86096. * Reset the {BABYLON.AssetsManager} and remove all tasks
  86097. * @return the current instance of the {BABYLON.AssetsManager}
  86098. */
  86099. AssetsManager.prototype.reset = function () {
  86100. this._isLoading = false;
  86101. this._tasks = new Array();
  86102. return this;
  86103. };
  86104. /**
  86105. * Start the loading process
  86106. * @return the current instance of the {BABYLON.AssetsManager}
  86107. */
  86108. AssetsManager.prototype.load = function () {
  86109. if (this._isLoading) {
  86110. return this;
  86111. }
  86112. this._isLoading = true;
  86113. this._waitingTasksCount = this._tasks.length;
  86114. this._totalTasksCount = this._tasks.length;
  86115. if (this._waitingTasksCount === 0) {
  86116. this._isLoading = false;
  86117. if (this.onFinish) {
  86118. this.onFinish(this._tasks);
  86119. }
  86120. this.onTasksDoneObservable.notifyObservers(this._tasks);
  86121. return this;
  86122. }
  86123. if (this.useDefaultLoadingScreen) {
  86124. this._scene.getEngine().displayLoadingUI();
  86125. }
  86126. for (var index = 0; index < this._tasks.length; index++) {
  86127. var task = this._tasks[index];
  86128. this._runTask(task);
  86129. }
  86130. return this;
  86131. };
  86132. return AssetsManager;
  86133. }());
  86134. BABYLON.AssetsManager = AssetsManager;
  86135. })(BABYLON || (BABYLON = {}));
  86136. //# sourceMappingURL=babylon.assetsManager.js.map
  86137. var BABYLON;
  86138. (function (BABYLON) {
  86139. var serializedGeometries = [];
  86140. var serializeGeometry = function (geometry, serializationGeometries) {
  86141. if (serializedGeometries[geometry.id]) {
  86142. return;
  86143. }
  86144. if (geometry.doNotSerialize) {
  86145. return;
  86146. }
  86147. if (geometry instanceof BABYLON.BoxGeometry) {
  86148. serializationGeometries.boxes.push(geometry.serialize());
  86149. }
  86150. else if (geometry instanceof BABYLON.SphereGeometry) {
  86151. serializationGeometries.spheres.push(geometry.serialize());
  86152. }
  86153. else if (geometry instanceof BABYLON.CylinderGeometry) {
  86154. serializationGeometries.cylinders.push(geometry.serialize());
  86155. }
  86156. else if (geometry instanceof BABYLON.TorusGeometry) {
  86157. serializationGeometries.toruses.push(geometry.serialize());
  86158. }
  86159. else if (geometry instanceof BABYLON.GroundGeometry) {
  86160. serializationGeometries.grounds.push(geometry.serialize());
  86161. }
  86162. else if (geometry instanceof BABYLON.Plane) {
  86163. serializationGeometries.planes.push(geometry.serialize());
  86164. }
  86165. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  86166. serializationGeometries.torusKnots.push(geometry.serialize());
  86167. }
  86168. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  86169. throw new Error("Unknown primitive type");
  86170. }
  86171. else {
  86172. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  86173. }
  86174. serializedGeometries[geometry.id] = true;
  86175. };
  86176. var serializeMesh = function (mesh, serializationScene) {
  86177. var serializationObject = {};
  86178. // Geometry
  86179. var geometry = mesh._geometry;
  86180. if (geometry) {
  86181. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  86182. // 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
  86183. serializeGeometry(geometry, serializationScene.geometries);
  86184. }
  86185. }
  86186. // Custom
  86187. if (mesh.serialize) {
  86188. mesh.serialize(serializationObject);
  86189. }
  86190. return serializationObject;
  86191. };
  86192. var finalizeSingleMesh = function (mesh, serializationObject) {
  86193. //only works if the mesh is already loaded
  86194. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  86195. //serialize material
  86196. if (mesh.material) {
  86197. if (mesh.material instanceof BABYLON.StandardMaterial) {
  86198. serializationObject.materials = serializationObject.materials || [];
  86199. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  86200. serializationObject.materials.push(mesh.material.serialize());
  86201. }
  86202. }
  86203. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  86204. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  86205. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  86206. serializationObject.multiMaterials.push(mesh.material.serialize());
  86207. }
  86208. }
  86209. }
  86210. //serialize geometry
  86211. var geometry = mesh._geometry;
  86212. if (geometry) {
  86213. if (!serializationObject.geometries) {
  86214. serializationObject.geometries = {};
  86215. serializationObject.geometries.boxes = [];
  86216. serializationObject.geometries.spheres = [];
  86217. serializationObject.geometries.cylinders = [];
  86218. serializationObject.geometries.toruses = [];
  86219. serializationObject.geometries.grounds = [];
  86220. serializationObject.geometries.planes = [];
  86221. serializationObject.geometries.torusKnots = [];
  86222. serializationObject.geometries.vertexData = [];
  86223. }
  86224. serializeGeometry(geometry, serializationObject.geometries);
  86225. }
  86226. // Skeletons
  86227. if (mesh.skeleton) {
  86228. serializationObject.skeletons = serializationObject.skeletons || [];
  86229. serializationObject.skeletons.push(mesh.skeleton.serialize());
  86230. }
  86231. //serialize the actual mesh
  86232. serializationObject.meshes = serializationObject.meshes || [];
  86233. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  86234. }
  86235. };
  86236. var SceneSerializer = /** @class */ (function () {
  86237. function SceneSerializer() {
  86238. }
  86239. SceneSerializer.ClearCache = function () {
  86240. serializedGeometries = [];
  86241. };
  86242. SceneSerializer.Serialize = function (scene) {
  86243. var serializationObject = {};
  86244. SceneSerializer.ClearCache();
  86245. // Scene
  86246. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  86247. serializationObject.autoClear = scene.autoClear;
  86248. serializationObject.clearColor = scene.clearColor.asArray();
  86249. serializationObject.ambientColor = scene.ambientColor.asArray();
  86250. serializationObject.gravity = scene.gravity.asArray();
  86251. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  86252. serializationObject.workerCollisions = scene.workerCollisions;
  86253. // Fog
  86254. if (scene.fogMode && scene.fogMode !== 0) {
  86255. serializationObject.fogMode = scene.fogMode;
  86256. serializationObject.fogColor = scene.fogColor.asArray();
  86257. serializationObject.fogStart = scene.fogStart;
  86258. serializationObject.fogEnd = scene.fogEnd;
  86259. serializationObject.fogDensity = scene.fogDensity;
  86260. }
  86261. //Physics
  86262. if (scene.isPhysicsEnabled()) {
  86263. var physicEngine = scene.getPhysicsEngine();
  86264. if (physicEngine) {
  86265. serializationObject.physicsEnabled = true;
  86266. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  86267. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  86268. }
  86269. }
  86270. // Metadata
  86271. if (scene.metadata) {
  86272. serializationObject.metadata = scene.metadata;
  86273. }
  86274. // Morph targets
  86275. serializationObject.morphTargetManagers = [];
  86276. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  86277. var abstractMesh = _a[_i];
  86278. var manager = abstractMesh.morphTargetManager;
  86279. if (manager) {
  86280. serializationObject.morphTargetManagers.push(manager.serialize());
  86281. }
  86282. }
  86283. // Lights
  86284. serializationObject.lights = [];
  86285. var index;
  86286. var light;
  86287. for (index = 0; index < scene.lights.length; index++) {
  86288. light = scene.lights[index];
  86289. if (!light.doNotSerialize) {
  86290. serializationObject.lights.push(light.serialize());
  86291. }
  86292. }
  86293. // Cameras
  86294. serializationObject.cameras = [];
  86295. for (index = 0; index < scene.cameras.length; index++) {
  86296. var camera = scene.cameras[index];
  86297. if (!camera.doNotSerialize) {
  86298. serializationObject.cameras.push(camera.serialize());
  86299. }
  86300. }
  86301. if (scene.activeCamera) {
  86302. serializationObject.activeCameraID = scene.activeCamera.id;
  86303. }
  86304. // Animations
  86305. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  86306. // Materials
  86307. serializationObject.materials = [];
  86308. serializationObject.multiMaterials = [];
  86309. var material;
  86310. for (index = 0; index < scene.materials.length; index++) {
  86311. material = scene.materials[index];
  86312. if (!material.doNotSerialize) {
  86313. serializationObject.materials.push(material.serialize());
  86314. }
  86315. }
  86316. // MultiMaterials
  86317. serializationObject.multiMaterials = [];
  86318. for (index = 0; index < scene.multiMaterials.length; index++) {
  86319. var multiMaterial = scene.multiMaterials[index];
  86320. serializationObject.multiMaterials.push(multiMaterial.serialize());
  86321. }
  86322. // Environment texture
  86323. if (scene.environmentTexture) {
  86324. serializationObject.environmentTexture = scene.environmentTexture.name;
  86325. }
  86326. // Skeletons
  86327. serializationObject.skeletons = [];
  86328. for (index = 0; index < scene.skeletons.length; index++) {
  86329. var skeleton = scene.skeletons[index];
  86330. if (!skeleton.doNotSerialize) {
  86331. serializationObject.skeletons.push(skeleton.serialize());
  86332. }
  86333. }
  86334. // Transform nodes
  86335. serializationObject.transformNodes = [];
  86336. for (index = 0; index < scene.transformNodes.length; index++) {
  86337. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  86338. }
  86339. // Geometries
  86340. serializationObject.geometries = {};
  86341. serializationObject.geometries.boxes = [];
  86342. serializationObject.geometries.spheres = [];
  86343. serializationObject.geometries.cylinders = [];
  86344. serializationObject.geometries.toruses = [];
  86345. serializationObject.geometries.grounds = [];
  86346. serializationObject.geometries.planes = [];
  86347. serializationObject.geometries.torusKnots = [];
  86348. serializationObject.geometries.vertexData = [];
  86349. serializedGeometries = [];
  86350. var geometries = scene.getGeometries();
  86351. for (index = 0; index < geometries.length; index++) {
  86352. var geometry = geometries[index];
  86353. if (geometry.isReady()) {
  86354. serializeGeometry(geometry, serializationObject.geometries);
  86355. }
  86356. }
  86357. // Meshes
  86358. serializationObject.meshes = [];
  86359. for (index = 0; index < scene.meshes.length; index++) {
  86360. var abstractMesh = scene.meshes[index];
  86361. if (abstractMesh instanceof BABYLON.Mesh) {
  86362. var mesh = abstractMesh;
  86363. if (!mesh.doNotSerialize) {
  86364. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  86365. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  86366. }
  86367. }
  86368. }
  86369. }
  86370. // Particles Systems
  86371. serializationObject.particleSystems = [];
  86372. for (index = 0; index < scene.particleSystems.length; index++) {
  86373. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  86374. }
  86375. // Lens flares
  86376. serializationObject.lensFlareSystems = [];
  86377. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  86378. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  86379. }
  86380. // Shadows
  86381. serializationObject.shadowGenerators = [];
  86382. for (index = 0; index < scene.lights.length; index++) {
  86383. light = scene.lights[index];
  86384. var shadowGenerator = light.getShadowGenerator();
  86385. if (shadowGenerator) {
  86386. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  86387. }
  86388. }
  86389. // Action Manager
  86390. if (scene.actionManager) {
  86391. serializationObject.actions = scene.actionManager.serialize("scene");
  86392. }
  86393. // Audio
  86394. serializationObject.sounds = [];
  86395. for (index = 0; index < scene.soundTracks.length; index++) {
  86396. var soundtrack = scene.soundTracks[index];
  86397. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  86398. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  86399. }
  86400. }
  86401. return serializationObject;
  86402. };
  86403. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  86404. if (withParents === void 0) { withParents = false; }
  86405. if (withChildren === void 0) { withChildren = false; }
  86406. var serializationObject = {};
  86407. SceneSerializer.ClearCache();
  86408. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  86409. if (withParents || withChildren) {
  86410. //deliberate for loop! not for each, appended should be processed as well.
  86411. for (var i = 0; i < toSerialize.length; ++i) {
  86412. if (withChildren) {
  86413. toSerialize[i].getDescendants().forEach(function (node) {
  86414. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  86415. toSerialize.push(node);
  86416. }
  86417. });
  86418. }
  86419. //make sure the array doesn't contain the object already
  86420. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  86421. toSerialize.push(toSerialize[i].parent);
  86422. }
  86423. }
  86424. }
  86425. toSerialize.forEach(function (mesh) {
  86426. finalizeSingleMesh(mesh, serializationObject);
  86427. });
  86428. return serializationObject;
  86429. };
  86430. return SceneSerializer;
  86431. }());
  86432. BABYLON.SceneSerializer = SceneSerializer;
  86433. })(BABYLON || (BABYLON = {}));
  86434. //# sourceMappingURL=babylon.sceneSerializer.js.map
  86435. var BABYLON;
  86436. (function (BABYLON) {
  86437. var ReflectionProbe = /** @class */ (function () {
  86438. function ReflectionProbe(name, size, scene, generateMipMaps) {
  86439. if (generateMipMaps === void 0) { generateMipMaps = true; }
  86440. var _this = this;
  86441. this.name = name;
  86442. this._viewMatrix = BABYLON.Matrix.Identity();
  86443. this._target = BABYLON.Vector3.Zero();
  86444. this._add = BABYLON.Vector3.Zero();
  86445. this._invertYAxis = false;
  86446. this.position = BABYLON.Vector3.Zero();
  86447. this._scene = scene;
  86448. this._scene.reflectionProbes.push(this);
  86449. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  86450. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  86451. switch (faceIndex) {
  86452. case 0:
  86453. _this._add.copyFromFloats(1, 0, 0);
  86454. break;
  86455. case 1:
  86456. _this._add.copyFromFloats(-1, 0, 0);
  86457. break;
  86458. case 2:
  86459. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  86460. break;
  86461. case 3:
  86462. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  86463. break;
  86464. case 4:
  86465. _this._add.copyFromFloats(0, 0, 1);
  86466. break;
  86467. case 5:
  86468. _this._add.copyFromFloats(0, 0, -1);
  86469. break;
  86470. }
  86471. if (_this._attachedMesh) {
  86472. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  86473. }
  86474. _this.position.addToRef(_this._add, _this._target);
  86475. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  86476. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  86477. scene._forcedViewPosition = _this.position;
  86478. });
  86479. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  86480. scene._forcedViewPosition = null;
  86481. scene.updateTransformMatrix(true);
  86482. });
  86483. if (scene.activeCamera) {
  86484. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  86485. }
  86486. }
  86487. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  86488. get: function () {
  86489. return this._renderTargetTexture.samples;
  86490. },
  86491. set: function (value) {
  86492. this._renderTargetTexture.samples = value;
  86493. },
  86494. enumerable: true,
  86495. configurable: true
  86496. });
  86497. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  86498. get: function () {
  86499. return this._renderTargetTexture.refreshRate;
  86500. },
  86501. set: function (value) {
  86502. this._renderTargetTexture.refreshRate = value;
  86503. },
  86504. enumerable: true,
  86505. configurable: true
  86506. });
  86507. ReflectionProbe.prototype.getScene = function () {
  86508. return this._scene;
  86509. };
  86510. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  86511. get: function () {
  86512. return this._renderTargetTexture;
  86513. },
  86514. enumerable: true,
  86515. configurable: true
  86516. });
  86517. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  86518. get: function () {
  86519. return this._renderTargetTexture.renderList;
  86520. },
  86521. enumerable: true,
  86522. configurable: true
  86523. });
  86524. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  86525. this._attachedMesh = mesh;
  86526. };
  86527. /**
  86528. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  86529. *
  86530. * @param renderingGroupId The rendering group id corresponding to its index
  86531. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  86532. */
  86533. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  86534. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  86535. };
  86536. ReflectionProbe.prototype.dispose = function () {
  86537. var index = this._scene.reflectionProbes.indexOf(this);
  86538. if (index !== -1) {
  86539. // Remove from the scene if found
  86540. this._scene.reflectionProbes.splice(index, 1);
  86541. }
  86542. if (this._renderTargetTexture) {
  86543. this._renderTargetTexture.dispose();
  86544. this._renderTargetTexture = null;
  86545. }
  86546. };
  86547. return ReflectionProbe;
  86548. }());
  86549. BABYLON.ReflectionProbe = ReflectionProbe;
  86550. })(BABYLON || (BABYLON = {}));
  86551. //# sourceMappingURL=babylon.reflectionProbe.js.map
  86552. var BABYLON;
  86553. (function (BABYLON) {
  86554. var Layer = /** @class */ (function () {
  86555. function Layer(name, imgUrl, scene, isBackground, color) {
  86556. this.name = name;
  86557. this.scale = new BABYLON.Vector2(1, 1);
  86558. this.offset = new BABYLON.Vector2(0, 0);
  86559. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  86560. this.layerMask = 0x0FFFFFFF;
  86561. this._vertexBuffers = {};
  86562. // Events
  86563. /**
  86564. * An event triggered when the layer is disposed.
  86565. * @type {BABYLON.Observable}
  86566. */
  86567. this.onDisposeObservable = new BABYLON.Observable();
  86568. /**
  86569. * An event triggered before rendering the scene
  86570. * @type {BABYLON.Observable}
  86571. */
  86572. this.onBeforeRenderObservable = new BABYLON.Observable();
  86573. /**
  86574. * An event triggered after rendering the scene
  86575. * @type {BABYLON.Observable}
  86576. */
  86577. this.onAfterRenderObservable = new BABYLON.Observable();
  86578. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  86579. this.isBackground = isBackground === undefined ? true : isBackground;
  86580. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  86581. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  86582. this._scene.layers.push(this);
  86583. var engine = this._scene.getEngine();
  86584. // VBO
  86585. var vertices = [];
  86586. vertices.push(1, 1);
  86587. vertices.push(-1, 1);
  86588. vertices.push(-1, -1);
  86589. vertices.push(1, -1);
  86590. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  86591. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  86592. this._createIndexBuffer();
  86593. // Effects
  86594. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  86595. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  86596. }
  86597. Object.defineProperty(Layer.prototype, "onDispose", {
  86598. set: function (callback) {
  86599. if (this._onDisposeObserver) {
  86600. this.onDisposeObservable.remove(this._onDisposeObserver);
  86601. }
  86602. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  86603. },
  86604. enumerable: true,
  86605. configurable: true
  86606. });
  86607. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  86608. set: function (callback) {
  86609. if (this._onBeforeRenderObserver) {
  86610. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  86611. }
  86612. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  86613. },
  86614. enumerable: true,
  86615. configurable: true
  86616. });
  86617. Object.defineProperty(Layer.prototype, "onAfterRender", {
  86618. set: function (callback) {
  86619. if (this._onAfterRenderObserver) {
  86620. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  86621. }
  86622. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  86623. },
  86624. enumerable: true,
  86625. configurable: true
  86626. });
  86627. Layer.prototype._createIndexBuffer = function () {
  86628. var engine = this._scene.getEngine();
  86629. // Indices
  86630. var indices = [];
  86631. indices.push(0);
  86632. indices.push(1);
  86633. indices.push(2);
  86634. indices.push(0);
  86635. indices.push(2);
  86636. indices.push(3);
  86637. this._indexBuffer = engine.createIndexBuffer(indices);
  86638. };
  86639. Layer.prototype._rebuild = function () {
  86640. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86641. if (vb) {
  86642. vb._rebuild();
  86643. }
  86644. this._createIndexBuffer();
  86645. };
  86646. Layer.prototype.render = function () {
  86647. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  86648. // Check
  86649. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  86650. return;
  86651. var engine = this._scene.getEngine();
  86652. this.onBeforeRenderObservable.notifyObservers(this);
  86653. // Render
  86654. engine.enableEffect(currentEffect);
  86655. engine.setState(false);
  86656. // Texture
  86657. currentEffect.setTexture("textureSampler", this.texture);
  86658. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  86659. // Color
  86660. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  86661. // Scale / offset
  86662. currentEffect.setVector2("offset", this.offset);
  86663. currentEffect.setVector2("scale", this.scale);
  86664. // VBOs
  86665. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  86666. // Draw order
  86667. if (!this.alphaTest) {
  86668. engine.setAlphaMode(this.alphaBlendingMode);
  86669. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86670. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  86671. }
  86672. else {
  86673. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86674. }
  86675. this.onAfterRenderObservable.notifyObservers(this);
  86676. };
  86677. Layer.prototype.dispose = function () {
  86678. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86679. if (vertexBuffer) {
  86680. vertexBuffer.dispose();
  86681. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86682. }
  86683. if (this._indexBuffer) {
  86684. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86685. this._indexBuffer = null;
  86686. }
  86687. if (this.texture) {
  86688. this.texture.dispose();
  86689. this.texture = null;
  86690. }
  86691. // Remove from scene
  86692. var index = this._scene.layers.indexOf(this);
  86693. this._scene.layers.splice(index, 1);
  86694. // Callback
  86695. this.onDisposeObservable.notifyObservers(this);
  86696. this.onDisposeObservable.clear();
  86697. this.onAfterRenderObservable.clear();
  86698. this.onBeforeRenderObservable.clear();
  86699. };
  86700. return Layer;
  86701. }());
  86702. BABYLON.Layer = Layer;
  86703. })(BABYLON || (BABYLON = {}));
  86704. //# sourceMappingURL=babylon.layer.js.map
  86705. var BABYLON;
  86706. (function (BABYLON) {
  86707. var TextureTools = /** @class */ (function () {
  86708. function TextureTools() {
  86709. }
  86710. /**
  86711. * Uses the GPU to create a copy texture rescaled at a given size
  86712. * @param texture Texture to copy from
  86713. * @param width Desired width
  86714. * @param height Desired height
  86715. * @return Generated texture
  86716. */
  86717. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  86718. if (useBilinearMode === void 0) { useBilinearMode = true; }
  86719. var scene = texture.getScene();
  86720. var engine = scene.getEngine();
  86721. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  86722. rtt.wrapU = texture.wrapU;
  86723. rtt.wrapV = texture.wrapV;
  86724. rtt.uOffset = texture.uOffset;
  86725. rtt.vOffset = texture.vOffset;
  86726. rtt.uScale = texture.uScale;
  86727. rtt.vScale = texture.vScale;
  86728. rtt.uAng = texture.uAng;
  86729. rtt.vAng = texture.vAng;
  86730. rtt.wAng = texture.wAng;
  86731. rtt.coordinatesIndex = texture.coordinatesIndex;
  86732. rtt.level = texture.level;
  86733. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  86734. rtt._texture.isReady = false;
  86735. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86736. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86737. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  86738. passPostProcess.getEffect().executeWhenCompiled(function () {
  86739. passPostProcess.onApply = function (effect) {
  86740. effect.setTexture("textureSampler", texture);
  86741. };
  86742. var internalTexture = rtt.getInternalTexture();
  86743. if (internalTexture) {
  86744. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  86745. engine.unBindFramebuffer(internalTexture);
  86746. rtt.disposeFramebufferObjects();
  86747. passPostProcess.dispose();
  86748. internalTexture.isReady = true;
  86749. }
  86750. });
  86751. return rtt;
  86752. };
  86753. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  86754. if (!scene._environmentBRDFTexture) {
  86755. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86756. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86757. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86758. scene._environmentBRDFTexture = texture;
  86759. }
  86760. return scene._environmentBRDFTexture;
  86761. };
  86762. 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=";
  86763. return TextureTools;
  86764. }());
  86765. BABYLON.TextureTools = TextureTools;
  86766. })(BABYLON || (BABYLON = {}));
  86767. //# sourceMappingURL=babylon.textureTools.js.map
  86768. var BABYLON;
  86769. (function (BABYLON) {
  86770. var FramingBehavior = /** @class */ (function () {
  86771. function FramingBehavior() {
  86772. this._mode = FramingBehavior.FitFrustumSidesMode;
  86773. this._radiusScale = 1.0;
  86774. this._positionScale = 0.5;
  86775. this._defaultElevation = 0.3;
  86776. this._elevationReturnTime = 1500;
  86777. this._elevationReturnWaitTime = 1000;
  86778. this._zoomStopsAnimation = false;
  86779. this._framingTime = 1500;
  86780. this._isPointerDown = false;
  86781. this._lastInteractionTime = -Infinity;
  86782. // Framing control
  86783. this._animatables = new Array();
  86784. this._betaIsAnimating = false;
  86785. }
  86786. Object.defineProperty(FramingBehavior.prototype, "name", {
  86787. get: function () {
  86788. return "Framing";
  86789. },
  86790. enumerable: true,
  86791. configurable: true
  86792. });
  86793. Object.defineProperty(FramingBehavior.prototype, "mode", {
  86794. /**
  86795. * Gets current mode used by the behavior.
  86796. */
  86797. get: function () {
  86798. return this._mode;
  86799. },
  86800. /**
  86801. * Sets the current mode used by the behavior
  86802. */
  86803. set: function (mode) {
  86804. this._mode = mode;
  86805. },
  86806. enumerable: true,
  86807. configurable: true
  86808. });
  86809. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  86810. /**
  86811. * Gets the scale applied to the radius
  86812. */
  86813. get: function () {
  86814. return this._radiusScale;
  86815. },
  86816. /**
  86817. * Sets the scale applied to the radius (1 by default)
  86818. */
  86819. set: function (radius) {
  86820. this._radiusScale = radius;
  86821. },
  86822. enumerable: true,
  86823. configurable: true
  86824. });
  86825. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  86826. /**
  86827. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  86828. */
  86829. get: function () {
  86830. return this._positionScale;
  86831. },
  86832. /**
  86833. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  86834. */
  86835. set: function (scale) {
  86836. this._positionScale = scale;
  86837. },
  86838. enumerable: true,
  86839. configurable: true
  86840. });
  86841. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  86842. /**
  86843. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  86844. * behaviour is triggered, in radians.
  86845. */
  86846. get: function () {
  86847. return this._defaultElevation;
  86848. },
  86849. /**
  86850. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  86851. * behaviour is triggered, in radians.
  86852. */
  86853. set: function (elevation) {
  86854. this._defaultElevation = elevation;
  86855. },
  86856. enumerable: true,
  86857. configurable: true
  86858. });
  86859. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  86860. /**
  86861. * Gets the time (in milliseconds) taken to return to the default beta position.
  86862. * Negative value indicates camera should not return to default.
  86863. */
  86864. get: function () {
  86865. return this._elevationReturnTime;
  86866. },
  86867. /**
  86868. * Sets the time (in milliseconds) taken to return to the default beta position.
  86869. * Negative value indicates camera should not return to default.
  86870. */
  86871. set: function (speed) {
  86872. this._elevationReturnTime = speed;
  86873. },
  86874. enumerable: true,
  86875. configurable: true
  86876. });
  86877. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  86878. /**
  86879. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  86880. */
  86881. get: function () {
  86882. return this._elevationReturnWaitTime;
  86883. },
  86884. /**
  86885. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  86886. */
  86887. set: function (time) {
  86888. this._elevationReturnWaitTime = time;
  86889. },
  86890. enumerable: true,
  86891. configurable: true
  86892. });
  86893. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  86894. /**
  86895. * Gets the flag that indicates if user zooming should stop animation.
  86896. */
  86897. get: function () {
  86898. return this._zoomStopsAnimation;
  86899. },
  86900. /**
  86901. * Sets the flag that indicates if user zooming should stop animation.
  86902. */
  86903. set: function (flag) {
  86904. this._zoomStopsAnimation = flag;
  86905. },
  86906. enumerable: true,
  86907. configurable: true
  86908. });
  86909. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  86910. /**
  86911. * Gets the transition time when framing the mesh, in milliseconds
  86912. */
  86913. get: function () {
  86914. return this._framingTime;
  86915. },
  86916. /**
  86917. * Sets the transition time when framing the mesh, in milliseconds
  86918. */
  86919. set: function (time) {
  86920. this._framingTime = time;
  86921. },
  86922. enumerable: true,
  86923. configurable: true
  86924. });
  86925. FramingBehavior.prototype.init = function () {
  86926. // Do notihng
  86927. };
  86928. FramingBehavior.prototype.attach = function (camera) {
  86929. var _this = this;
  86930. this._attachedCamera = camera;
  86931. var scene = this._attachedCamera.getScene();
  86932. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  86933. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  86934. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  86935. _this._isPointerDown = true;
  86936. return;
  86937. }
  86938. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  86939. _this._isPointerDown = false;
  86940. }
  86941. });
  86942. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  86943. if (mesh) {
  86944. _this.zoomOnMesh(mesh);
  86945. }
  86946. });
  86947. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  86948. // Stop the animation if there is user interaction and the animation should stop for this interaction
  86949. _this._applyUserInteraction();
  86950. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  86951. // back to the default position after a given timeout
  86952. _this._maintainCameraAboveGround();
  86953. });
  86954. };
  86955. FramingBehavior.prototype.detach = function () {
  86956. if (!this._attachedCamera) {
  86957. return;
  86958. }
  86959. var scene = this._attachedCamera.getScene();
  86960. if (this._onPrePointerObservableObserver) {
  86961. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  86962. }
  86963. if (this._onAfterCheckInputsObserver) {
  86964. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  86965. }
  86966. if (this._onMeshTargetChangedObserver) {
  86967. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  86968. }
  86969. this._attachedCamera = null;
  86970. };
  86971. /**
  86972. * Targets the given mesh and updates zoom level accordingly.
  86973. * @param mesh The mesh to target.
  86974. * @param radius Optional. If a cached radius position already exists, overrides default.
  86975. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  86976. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  86977. * @param onAnimationEnd Callback triggered at the end of the framing animation
  86978. */
  86979. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  86980. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  86981. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  86982. mesh.computeWorldMatrix(true);
  86983. var boundingBox = mesh.getBoundingInfo().boundingBox;
  86984. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  86985. };
  86986. /**
  86987. * Targets the given mesh with its children and updates zoom level accordingly.
  86988. * @param mesh The mesh to target.
  86989. * @param radius Optional. If a cached radius position already exists, overrides default.
  86990. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  86991. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  86992. * @param onAnimationEnd Callback triggered at the end of the framing animation
  86993. */
  86994. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  86995. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  86996. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  86997. mesh.computeWorldMatrix(true);
  86998. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  86999. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  87000. };
  87001. /**
  87002. * Targets the given meshes with their children and updates zoom level accordingly.
  87003. * @param meshes The mesh to target.
  87004. * @param radius Optional. If a cached radius position already exists, overrides default.
  87005. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87006. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87007. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87008. */
  87009. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  87010. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87011. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87012. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  87013. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  87014. for (var i = 0; i < meshes.length; i++) {
  87015. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  87016. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  87017. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  87018. }
  87019. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  87020. };
  87021. /**
  87022. * Targets the given mesh and updates zoom level accordingly.
  87023. * @param mesh The mesh to target.
  87024. * @param radius Optional. If a cached radius position already exists, overrides default.
  87025. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87026. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87027. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87028. */
  87029. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  87030. var _this = this;
  87031. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87032. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87033. var zoomTarget;
  87034. if (!this._attachedCamera) {
  87035. return;
  87036. }
  87037. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  87038. var bottom = minimumWorld.y;
  87039. var top = maximumWorld.y;
  87040. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  87041. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  87042. if (focusOnOriginXZ) {
  87043. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  87044. }
  87045. else {
  87046. var centerWorld = minimumWorld.add(radiusWorld);
  87047. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  87048. }
  87049. if (!this._vectorTransition) {
  87050. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  87051. }
  87052. this._betaIsAnimating = true;
  87053. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  87054. if (animatable) {
  87055. this._animatables.push(animatable);
  87056. }
  87057. // sets the radius and lower radius bounds
  87058. // Small delta ensures camera is not always at lower zoom limit.
  87059. var radius = 0;
  87060. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  87061. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  87062. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  87063. radius = position;
  87064. }
  87065. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  87066. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  87067. if (this._attachedCamera.lowerRadiusLimit === null) {
  87068. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  87069. }
  87070. }
  87071. // Set sensibilities
  87072. var extend = maximumWorld.subtract(minimumWorld).length();
  87073. this._attachedCamera.panningSensibility = 5000 / extend;
  87074. this._attachedCamera.wheelPrecision = 100 / radius;
  87075. // transition to new radius
  87076. if (!this._radiusTransition) {
  87077. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  87078. }
  87079. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  87080. if (onAnimationEnd) {
  87081. onAnimationEnd();
  87082. }
  87083. if (_this._attachedCamera) {
  87084. _this._attachedCamera.storeState();
  87085. }
  87086. });
  87087. if (animatable) {
  87088. this._animatables.push(animatable);
  87089. }
  87090. };
  87091. /**
  87092. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  87093. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  87094. * frustum width.
  87095. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  87096. * to fully enclose the mesh in the viewing frustum.
  87097. */
  87098. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  87099. var size = maximumWorld.subtract(minimumWorld);
  87100. var boxVectorGlobalDiagonal = size.length();
  87101. var frustumSlope = this._getFrustumSlope();
  87102. // Formula for setting distance
  87103. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  87104. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  87105. // Horizon distance
  87106. var radius = radiusWithoutFraming * this._radiusScale;
  87107. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  87108. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  87109. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  87110. var camera = this._attachedCamera;
  87111. if (!camera) {
  87112. return 0;
  87113. }
  87114. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  87115. // Don't exceed the requested limit
  87116. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  87117. }
  87118. // Don't exceed the upper radius limit
  87119. if (camera.upperRadiusLimit) {
  87120. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  87121. }
  87122. return distance;
  87123. };
  87124. /**
  87125. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  87126. * is automatically returned to its default position (expected to be above ground plane).
  87127. */
  87128. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  87129. var _this = this;
  87130. if (this._elevationReturnTime < 0) {
  87131. return;
  87132. }
  87133. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  87134. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  87135. var limitBeta = Math.PI * 0.5;
  87136. // Bring the camera back up if below the ground plane
  87137. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  87138. this._betaIsAnimating = true;
  87139. //Transition to new position
  87140. this.stopAllAnimations();
  87141. if (!this._betaTransition) {
  87142. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  87143. }
  87144. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  87145. _this._clearAnimationLocks();
  87146. _this.stopAllAnimations();
  87147. });
  87148. if (animatabe) {
  87149. this._animatables.push(animatabe);
  87150. }
  87151. }
  87152. };
  87153. /**
  87154. * Returns the frustum slope based on the canvas ratio and camera FOV
  87155. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  87156. */
  87157. FramingBehavior.prototype._getFrustumSlope = function () {
  87158. // Calculate the viewport ratio
  87159. // Aspect Ratio is Height/Width.
  87160. var camera = this._attachedCamera;
  87161. if (!camera) {
  87162. return BABYLON.Vector2.Zero();
  87163. }
  87164. var engine = camera.getScene().getEngine();
  87165. var aspectRatio = engine.getAspectRatio(camera);
  87166. // Camera FOV is the vertical field of view (top-bottom) in radians.
  87167. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  87168. var frustumSlopeY = Math.tan(camera.fov / 2);
  87169. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  87170. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  87171. // along the forward vector.
  87172. var frustumSlopeX = frustumSlopeY * aspectRatio;
  87173. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  87174. };
  87175. /**
  87176. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  87177. */
  87178. FramingBehavior.prototype._clearAnimationLocks = function () {
  87179. this._betaIsAnimating = false;
  87180. };
  87181. /**
  87182. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  87183. */
  87184. FramingBehavior.prototype._applyUserInteraction = function () {
  87185. if (this.isUserIsMoving) {
  87186. this._lastInteractionTime = BABYLON.Tools.Now;
  87187. this.stopAllAnimations();
  87188. this._clearAnimationLocks();
  87189. }
  87190. };
  87191. /**
  87192. * Stops and removes all animations that have been applied to the camera
  87193. */
  87194. FramingBehavior.prototype.stopAllAnimations = function () {
  87195. if (this._attachedCamera) {
  87196. this._attachedCamera.animations = [];
  87197. }
  87198. while (this._animatables.length) {
  87199. if (this._animatables[0]) {
  87200. this._animatables[0].onAnimationEnd = null;
  87201. this._animatables[0].stop();
  87202. }
  87203. this._animatables.shift();
  87204. }
  87205. };
  87206. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  87207. /**
  87208. * Gets a value indicating if the user is moving the camera
  87209. */
  87210. get: function () {
  87211. if (!this._attachedCamera) {
  87212. return false;
  87213. }
  87214. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  87215. this._attachedCamera.inertialBetaOffset !== 0 ||
  87216. this._attachedCamera.inertialRadiusOffset !== 0 ||
  87217. this._attachedCamera.inertialPanningX !== 0 ||
  87218. this._attachedCamera.inertialPanningY !== 0 ||
  87219. this._isPointerDown;
  87220. },
  87221. enumerable: true,
  87222. configurable: true
  87223. });
  87224. /**
  87225. * The easing function used by animations
  87226. */
  87227. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  87228. /**
  87229. * The easing mode used by animations
  87230. */
  87231. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  87232. // Statics
  87233. /**
  87234. * The camera can move all the way towards the mesh.
  87235. */
  87236. FramingBehavior.IgnoreBoundsSizeMode = 0;
  87237. /**
  87238. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  87239. */
  87240. FramingBehavior.FitFrustumSidesMode = 1;
  87241. return FramingBehavior;
  87242. }());
  87243. BABYLON.FramingBehavior = FramingBehavior;
  87244. })(BABYLON || (BABYLON = {}));
  87245. //# sourceMappingURL=babylon.framingBehavior.js.map
  87246. var BABYLON;
  87247. (function (BABYLON) {
  87248. /**
  87249. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  87250. */
  87251. var BouncingBehavior = /** @class */ (function () {
  87252. function BouncingBehavior() {
  87253. /**
  87254. * The duration of the animation, in milliseconds
  87255. */
  87256. this.transitionDuration = 450;
  87257. /**
  87258. * Length of the distance animated by the transition when lower radius is reached
  87259. */
  87260. this.lowerRadiusTransitionRange = 2;
  87261. /**
  87262. * Length of the distance animated by the transition when upper radius is reached
  87263. */
  87264. this.upperRadiusTransitionRange = -2;
  87265. this._autoTransitionRange = false;
  87266. // Animations
  87267. this._radiusIsAnimating = false;
  87268. this._radiusBounceTransition = null;
  87269. this._animatables = new Array();
  87270. }
  87271. Object.defineProperty(BouncingBehavior.prototype, "name", {
  87272. get: function () {
  87273. return "Bouncing";
  87274. },
  87275. enumerable: true,
  87276. configurable: true
  87277. });
  87278. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  87279. /**
  87280. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  87281. */
  87282. get: function () {
  87283. return this._autoTransitionRange;
  87284. },
  87285. /**
  87286. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  87287. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  87288. */
  87289. set: function (value) {
  87290. var _this = this;
  87291. if (this._autoTransitionRange === value) {
  87292. return;
  87293. }
  87294. this._autoTransitionRange = value;
  87295. var camera = this._attachedCamera;
  87296. if (!camera) {
  87297. return;
  87298. }
  87299. if (value) {
  87300. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  87301. if (!mesh) {
  87302. return;
  87303. }
  87304. mesh.computeWorldMatrix(true);
  87305. var diagonal = mesh.getBoundingInfo().diagonalLength;
  87306. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  87307. _this.upperRadiusTransitionRange = diagonal * 0.05;
  87308. });
  87309. }
  87310. else if (this._onMeshTargetChangedObserver) {
  87311. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  87312. }
  87313. },
  87314. enumerable: true,
  87315. configurable: true
  87316. });
  87317. BouncingBehavior.prototype.init = function () {
  87318. // Do notihng
  87319. };
  87320. BouncingBehavior.prototype.attach = function (camera) {
  87321. var _this = this;
  87322. this._attachedCamera = camera;
  87323. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  87324. if (!_this._attachedCamera) {
  87325. return;
  87326. }
  87327. // Add the bounce animation to the lower radius limit
  87328. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  87329. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  87330. }
  87331. // Add the bounce animation to the upper radius limit
  87332. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  87333. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  87334. }
  87335. });
  87336. };
  87337. BouncingBehavior.prototype.detach = function () {
  87338. if (!this._attachedCamera) {
  87339. return;
  87340. }
  87341. if (this._onAfterCheckInputsObserver) {
  87342. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  87343. }
  87344. if (this._onMeshTargetChangedObserver) {
  87345. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  87346. }
  87347. this._attachedCamera = null;
  87348. };
  87349. /**
  87350. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  87351. * @param radiusLimit The limit to check against.
  87352. * @return Bool to indicate if at limit.
  87353. */
  87354. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  87355. if (!this._attachedCamera) {
  87356. return false;
  87357. }
  87358. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  87359. return true;
  87360. }
  87361. return false;
  87362. };
  87363. /**
  87364. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  87365. * @param radiusDelta The delta by which to animate to. Can be negative.
  87366. */
  87367. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  87368. var _this = this;
  87369. if (!this._attachedCamera) {
  87370. return;
  87371. }
  87372. if (!this._radiusBounceTransition) {
  87373. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  87374. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  87375. }
  87376. // Prevent zoom until bounce has completed
  87377. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  87378. this._attachedCamera.wheelPrecision = Infinity;
  87379. this._attachedCamera.inertialRadiusOffset = 0;
  87380. // Animate to the radius limit
  87381. this.stopAllAnimations();
  87382. this._radiusIsAnimating = true;
  87383. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  87384. if (animatable) {
  87385. this._animatables.push(animatable);
  87386. }
  87387. };
  87388. /**
  87389. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  87390. */
  87391. BouncingBehavior.prototype._clearAnimationLocks = function () {
  87392. this._radiusIsAnimating = false;
  87393. if (this._attachedCamera) {
  87394. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  87395. }
  87396. };
  87397. /**
  87398. * Stops and removes all animations that have been applied to the camera
  87399. */
  87400. BouncingBehavior.prototype.stopAllAnimations = function () {
  87401. if (this._attachedCamera) {
  87402. this._attachedCamera.animations = [];
  87403. }
  87404. while (this._animatables.length) {
  87405. this._animatables[0].onAnimationEnd = null;
  87406. this._animatables[0].stop();
  87407. this._animatables.shift();
  87408. }
  87409. };
  87410. /**
  87411. * The easing function used by animations
  87412. */
  87413. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  87414. /**
  87415. * The easing mode used by animations
  87416. */
  87417. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  87418. return BouncingBehavior;
  87419. }());
  87420. BABYLON.BouncingBehavior = BouncingBehavior;
  87421. })(BABYLON || (BABYLON = {}));
  87422. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  87423. var BABYLON;
  87424. (function (BABYLON) {
  87425. var AutoRotationBehavior = /** @class */ (function () {
  87426. function AutoRotationBehavior() {
  87427. this._zoomStopsAnimation = false;
  87428. this._idleRotationSpeed = 0.05;
  87429. this._idleRotationWaitTime = 2000;
  87430. this._idleRotationSpinupTime = 2000;
  87431. this._isPointerDown = false;
  87432. this._lastFrameTime = null;
  87433. this._lastInteractionTime = -Infinity;
  87434. this._cameraRotationSpeed = 0;
  87435. this._lastFrameRadius = 0;
  87436. }
  87437. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  87438. get: function () {
  87439. return "AutoRotation";
  87440. },
  87441. enumerable: true,
  87442. configurable: true
  87443. });
  87444. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  87445. /**
  87446. * Gets the flag that indicates if user zooming should stop animation.
  87447. */
  87448. get: function () {
  87449. return this._zoomStopsAnimation;
  87450. },
  87451. /**
  87452. * Sets the flag that indicates if user zooming should stop animation.
  87453. */
  87454. set: function (flag) {
  87455. this._zoomStopsAnimation = flag;
  87456. },
  87457. enumerable: true,
  87458. configurable: true
  87459. });
  87460. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  87461. /**
  87462. * Gets the default speed at which the camera rotates around the model.
  87463. */
  87464. get: function () {
  87465. return this._idleRotationSpeed;
  87466. },
  87467. /**
  87468. * Sets the default speed at which the camera rotates around the model.
  87469. */
  87470. set: function (speed) {
  87471. this._idleRotationSpeed = speed;
  87472. },
  87473. enumerable: true,
  87474. configurable: true
  87475. });
  87476. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  87477. /**
  87478. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  87479. */
  87480. get: function () {
  87481. return this._idleRotationWaitTime;
  87482. },
  87483. /**
  87484. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  87485. */
  87486. set: function (time) {
  87487. this._idleRotationWaitTime = time;
  87488. },
  87489. enumerable: true,
  87490. configurable: true
  87491. });
  87492. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  87493. /**
  87494. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  87495. */
  87496. get: function () {
  87497. return this._idleRotationSpinupTime;
  87498. },
  87499. /**
  87500. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  87501. */
  87502. set: function (time) {
  87503. this._idleRotationSpinupTime = time;
  87504. },
  87505. enumerable: true,
  87506. configurable: true
  87507. });
  87508. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  87509. /**
  87510. * Gets a value indicating if the camera is currently rotating because of this behavior
  87511. */
  87512. get: function () {
  87513. return Math.abs(this._cameraRotationSpeed) > 0;
  87514. },
  87515. enumerable: true,
  87516. configurable: true
  87517. });
  87518. AutoRotationBehavior.prototype.init = function () {
  87519. // Do notihng
  87520. };
  87521. AutoRotationBehavior.prototype.attach = function (camera) {
  87522. var _this = this;
  87523. this._attachedCamera = camera;
  87524. var scene = this._attachedCamera.getScene();
  87525. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  87526. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  87527. _this._isPointerDown = true;
  87528. return;
  87529. }
  87530. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  87531. _this._isPointerDown = false;
  87532. }
  87533. });
  87534. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  87535. var now = BABYLON.Tools.Now;
  87536. var dt = 0;
  87537. if (_this._lastFrameTime != null) {
  87538. dt = now - _this._lastFrameTime;
  87539. }
  87540. _this._lastFrameTime = now;
  87541. // Stop the animation if there is user interaction and the animation should stop for this interaction
  87542. _this._applyUserInteraction();
  87543. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  87544. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  87545. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  87546. // Step camera rotation by rotation speed
  87547. if (_this._attachedCamera) {
  87548. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  87549. }
  87550. });
  87551. };
  87552. AutoRotationBehavior.prototype.detach = function () {
  87553. if (!this._attachedCamera) {
  87554. return;
  87555. }
  87556. var scene = this._attachedCamera.getScene();
  87557. if (this._onPrePointerObservableObserver) {
  87558. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  87559. }
  87560. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  87561. this._attachedCamera = null;
  87562. };
  87563. /**
  87564. * Returns true if user is scrolling.
  87565. * @return true if user is scrolling.
  87566. */
  87567. AutoRotationBehavior.prototype._userIsZooming = function () {
  87568. if (!this._attachedCamera) {
  87569. return false;
  87570. }
  87571. return this._attachedCamera.inertialRadiusOffset !== 0;
  87572. };
  87573. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  87574. if (!this._attachedCamera) {
  87575. return false;
  87576. }
  87577. var zoomHasHitLimit = false;
  87578. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  87579. zoomHasHitLimit = true;
  87580. }
  87581. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  87582. this._lastFrameRadius = this._attachedCamera.radius;
  87583. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  87584. };
  87585. /**
  87586. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  87587. */
  87588. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  87589. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  87590. this._lastInteractionTime = BABYLON.Tools.Now;
  87591. }
  87592. };
  87593. // Tools
  87594. AutoRotationBehavior.prototype._userIsMoving = function () {
  87595. if (!this._attachedCamera) {
  87596. return false;
  87597. }
  87598. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  87599. this._attachedCamera.inertialBetaOffset !== 0 ||
  87600. this._attachedCamera.inertialRadiusOffset !== 0 ||
  87601. this._attachedCamera.inertialPanningX !== 0 ||
  87602. this._attachedCamera.inertialPanningY !== 0 ||
  87603. this._isPointerDown;
  87604. };
  87605. return AutoRotationBehavior;
  87606. }());
  87607. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  87608. })(BABYLON || (BABYLON = {}));
  87609. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  87610. var BABYLON;
  87611. (function (BABYLON) {
  87612. var NullEngineOptions = /** @class */ (function () {
  87613. function NullEngineOptions() {
  87614. this.renderWidth = 512;
  87615. this.renderHeight = 256;
  87616. this.textureSize = 512;
  87617. this.deterministicLockstep = false;
  87618. this.lockstepMaxSteps = 4;
  87619. }
  87620. return NullEngineOptions;
  87621. }());
  87622. BABYLON.NullEngineOptions = NullEngineOptions;
  87623. /**
  87624. * The null engine class provides support for headless version of babylon.js.
  87625. * This can be used in server side scenario or for testing purposes
  87626. */
  87627. var NullEngine = /** @class */ (function (_super) {
  87628. __extends(NullEngine, _super);
  87629. function NullEngine(options) {
  87630. if (options === void 0) { options = new NullEngineOptions(); }
  87631. var _this = _super.call(this, null) || this;
  87632. if (options.deterministicLockstep === undefined) {
  87633. options.deterministicLockstep = false;
  87634. }
  87635. if (options.lockstepMaxSteps === undefined) {
  87636. options.lockstepMaxSteps = 4;
  87637. }
  87638. _this._options = options;
  87639. // Init caps
  87640. // We consider we are on a webgl1 capable device
  87641. _this._caps = new BABYLON.EngineCapabilities();
  87642. _this._caps.maxTexturesImageUnits = 16;
  87643. _this._caps.maxVertexTextureImageUnits = 16;
  87644. _this._caps.maxTextureSize = 512;
  87645. _this._caps.maxCubemapTextureSize = 512;
  87646. _this._caps.maxRenderTextureSize = 512;
  87647. _this._caps.maxVertexAttribs = 16;
  87648. _this._caps.maxVaryingVectors = 16;
  87649. _this._caps.maxFragmentUniformVectors = 16;
  87650. _this._caps.maxVertexUniformVectors = 16;
  87651. // Extensions
  87652. _this._caps.standardDerivatives = false;
  87653. _this._caps.astc = null;
  87654. _this._caps.s3tc = null;
  87655. _this._caps.pvrtc = null;
  87656. _this._caps.etc1 = null;
  87657. _this._caps.etc2 = null;
  87658. _this._caps.textureAnisotropicFilterExtension = null;
  87659. _this._caps.maxAnisotropy = 0;
  87660. _this._caps.uintIndices = false;
  87661. _this._caps.fragmentDepthSupported = false;
  87662. _this._caps.highPrecisionShaderSupported = true;
  87663. _this._caps.colorBufferFloat = false;
  87664. _this._caps.textureFloat = false;
  87665. _this._caps.textureFloatLinearFiltering = false;
  87666. _this._caps.textureFloatRender = false;
  87667. _this._caps.textureHalfFloat = false;
  87668. _this._caps.textureHalfFloatLinearFiltering = false;
  87669. _this._caps.textureHalfFloatRender = false;
  87670. _this._caps.textureLOD = false;
  87671. _this._caps.drawBuffersExtension = false;
  87672. _this._caps.depthTextureExtension = false;
  87673. _this._caps.vertexArrayObject = false;
  87674. _this._caps.instancedArrays = false;
  87675. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  87676. // Wrappers
  87677. if (typeof URL === "undefined") {
  87678. URL = {
  87679. createObjectURL: function () { },
  87680. revokeObjectURL: function () { }
  87681. };
  87682. }
  87683. if (typeof Blob === "undefined") {
  87684. Blob = function () { };
  87685. }
  87686. return _this;
  87687. }
  87688. NullEngine.prototype.isDeterministicLockStep = function () {
  87689. return this._options.deterministicLockstep;
  87690. };
  87691. NullEngine.prototype.getLockstepMaxSteps = function () {
  87692. return this._options.lockstepMaxSteps;
  87693. };
  87694. NullEngine.prototype.getHardwareScalingLevel = function () {
  87695. return 1.0;
  87696. };
  87697. NullEngine.prototype.createVertexBuffer = function (vertices) {
  87698. return {
  87699. capacity: 0,
  87700. references: 1,
  87701. is32Bits: false
  87702. };
  87703. };
  87704. NullEngine.prototype.createIndexBuffer = function (indices) {
  87705. return {
  87706. capacity: 0,
  87707. references: 1,
  87708. is32Bits: false
  87709. };
  87710. };
  87711. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  87712. if (stencil === void 0) { stencil = false; }
  87713. };
  87714. NullEngine.prototype.getRenderWidth = function (useScreen) {
  87715. if (useScreen === void 0) { useScreen = false; }
  87716. if (!useScreen && this._currentRenderTarget) {
  87717. return this._currentRenderTarget.width;
  87718. }
  87719. return this._options.renderWidth;
  87720. };
  87721. NullEngine.prototype.getRenderHeight = function (useScreen) {
  87722. if (useScreen === void 0) { useScreen = false; }
  87723. if (!useScreen && this._currentRenderTarget) {
  87724. return this._currentRenderTarget.height;
  87725. }
  87726. return this._options.renderHeight;
  87727. };
  87728. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  87729. this._cachedViewport = viewport;
  87730. };
  87731. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  87732. return {
  87733. transformFeedback: null,
  87734. __SPECTOR_rebuildProgram: null
  87735. };
  87736. };
  87737. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  87738. return [];
  87739. };
  87740. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  87741. return [];
  87742. };
  87743. NullEngine.prototype.bindSamplers = function (effect) {
  87744. this._currentEffect = null;
  87745. };
  87746. NullEngine.prototype.enableEffect = function (effect) {
  87747. this._currentEffect = effect;
  87748. if (effect.onBind) {
  87749. effect.onBind(effect);
  87750. }
  87751. effect.onBindObservable.notifyObservers(effect);
  87752. };
  87753. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  87754. if (zOffset === void 0) { zOffset = 0; }
  87755. if (reverseSide === void 0) { reverseSide = false; }
  87756. };
  87757. NullEngine.prototype.setIntArray = function (uniform, array) {
  87758. };
  87759. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  87760. };
  87761. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  87762. };
  87763. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  87764. };
  87765. NullEngine.prototype.setFloatArray = function (uniform, array) {
  87766. };
  87767. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  87768. };
  87769. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  87770. };
  87771. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  87772. };
  87773. NullEngine.prototype.setArray = function (uniform, array) {
  87774. };
  87775. NullEngine.prototype.setArray2 = function (uniform, array) {
  87776. };
  87777. NullEngine.prototype.setArray3 = function (uniform, array) {
  87778. };
  87779. NullEngine.prototype.setArray4 = function (uniform, array) {
  87780. };
  87781. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  87782. };
  87783. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  87784. };
  87785. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  87786. };
  87787. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  87788. };
  87789. NullEngine.prototype.setFloat = function (uniform, value) {
  87790. };
  87791. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  87792. };
  87793. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  87794. };
  87795. NullEngine.prototype.setBool = function (uniform, bool) {
  87796. };
  87797. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  87798. };
  87799. NullEngine.prototype.setColor3 = function (uniform, color3) {
  87800. };
  87801. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  87802. };
  87803. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  87804. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  87805. if (this._alphaMode === mode) {
  87806. return;
  87807. }
  87808. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  87809. if (!noDepthWriteChange) {
  87810. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  87811. }
  87812. this._alphaMode = mode;
  87813. };
  87814. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  87815. };
  87816. NullEngine.prototype.wipeCaches = function (bruteForce) {
  87817. if (this.preventCacheWipeBetweenFrames) {
  87818. return;
  87819. }
  87820. this.resetTextureCache();
  87821. this._currentEffect = null;
  87822. if (bruteForce) {
  87823. this._currentProgram = null;
  87824. this._stencilState.reset();
  87825. this._depthCullingState.reset();
  87826. this._alphaState.reset();
  87827. }
  87828. this._cachedVertexBuffers = null;
  87829. this._cachedIndexBuffer = null;
  87830. this._cachedEffectForVertexBuffers = null;
  87831. };
  87832. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  87833. };
  87834. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  87835. };
  87836. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  87837. };
  87838. NullEngine.prototype._createTexture = function () {
  87839. return {};
  87840. };
  87841. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  87842. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  87843. if (onLoad === void 0) { onLoad = null; }
  87844. if (onError === void 0) { onError = null; }
  87845. if (buffer === void 0) { buffer = null; }
  87846. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  87847. var url = String(urlArg);
  87848. texture.url = url;
  87849. texture.generateMipMaps = !noMipmap;
  87850. texture.samplingMode = samplingMode;
  87851. texture.invertY = invertY;
  87852. texture.baseWidth = this._options.textureSize;
  87853. texture.baseHeight = this._options.textureSize;
  87854. texture.width = this._options.textureSize;
  87855. texture.height = this._options.textureSize;
  87856. if (format) {
  87857. texture.format = format;
  87858. }
  87859. texture.isReady = true;
  87860. if (onLoad) {
  87861. onLoad();
  87862. }
  87863. return texture;
  87864. };
  87865. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  87866. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  87867. if (options !== undefined && typeof options === "object") {
  87868. fullOptions.generateMipMaps = options.generateMipMaps;
  87869. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  87870. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  87871. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  87872. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  87873. }
  87874. else {
  87875. fullOptions.generateMipMaps = options;
  87876. fullOptions.generateDepthBuffer = true;
  87877. fullOptions.generateStencilBuffer = false;
  87878. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87879. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  87880. }
  87881. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  87882. var width = size.width || size;
  87883. var height = size.height || size;
  87884. texture._depthStencilBuffer = {};
  87885. texture._framebuffer = {};
  87886. texture.baseWidth = width;
  87887. texture.baseHeight = height;
  87888. texture.width = width;
  87889. texture.height = height;
  87890. texture.isReady = true;
  87891. texture.samples = 1;
  87892. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  87893. texture.samplingMode = fullOptions.samplingMode;
  87894. texture.type = fullOptions.type;
  87895. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  87896. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  87897. return texture;
  87898. };
  87899. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  87900. texture.samplingMode = samplingMode;
  87901. };
  87902. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  87903. if (this._currentRenderTarget) {
  87904. this.unBindFramebuffer(this._currentRenderTarget);
  87905. }
  87906. this._currentRenderTarget = texture;
  87907. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  87908. if (this._cachedViewport && !forceFullscreenViewport) {
  87909. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  87910. }
  87911. };
  87912. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  87913. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  87914. this._currentRenderTarget = null;
  87915. if (onBeforeUnbind) {
  87916. if (texture._MSAAFramebuffer) {
  87917. this._currentFramebuffer = texture._framebuffer;
  87918. }
  87919. onBeforeUnbind();
  87920. }
  87921. this._currentFramebuffer = null;
  87922. };
  87923. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  87924. var vbo = {
  87925. capacity: 1,
  87926. references: 1,
  87927. is32Bits: false
  87928. };
  87929. return vbo;
  87930. };
  87931. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  87932. if (offset === void 0) { offset = 0; }
  87933. };
  87934. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  87935. };
  87936. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  87937. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  87938. this._boundTexturesCache[this._activeChannel] = texture;
  87939. }
  87940. };
  87941. NullEngine.prototype._bindTexture = function (channel, texture) {
  87942. if (channel < 0) {
  87943. return;
  87944. }
  87945. this._bindTextureDirectly(0, texture);
  87946. };
  87947. NullEngine.prototype._releaseBuffer = function (buffer) {
  87948. buffer.references--;
  87949. if (buffer.references === 0) {
  87950. return true;
  87951. }
  87952. return false;
  87953. };
  87954. return NullEngine;
  87955. }(BABYLON.Engine));
  87956. BABYLON.NullEngine = NullEngine;
  87957. })(BABYLON || (BABYLON = {}));
  87958. //# sourceMappingURL=babylon.nullEngine.js.map
  87959. var BABYLON;
  87960. (function (BABYLON) {
  87961. /**
  87962. * This class can be used to get instrumentation data from a Babylon engine
  87963. */
  87964. var EngineInstrumentation = /** @class */ (function () {
  87965. function EngineInstrumentation(engine) {
  87966. this.engine = engine;
  87967. this._captureGPUFrameTime = false;
  87968. this._gpuFrameTime = new BABYLON.PerfCounter();
  87969. this._captureShaderCompilationTime = false;
  87970. this._shaderCompilationTime = new BABYLON.PerfCounter();
  87971. // Observers
  87972. this._onBeginFrameObserver = null;
  87973. this._onEndFrameObserver = null;
  87974. this._onBeforeShaderCompilationObserver = null;
  87975. this._onAfterShaderCompilationObserver = null;
  87976. }
  87977. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  87978. // Properties
  87979. /**
  87980. * Gets the perf counter used for GPU frame time
  87981. */
  87982. get: function () {
  87983. return this._gpuFrameTime;
  87984. },
  87985. enumerable: true,
  87986. configurable: true
  87987. });
  87988. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  87989. /**
  87990. * Gets the GPU frame time capture status
  87991. */
  87992. get: function () {
  87993. return this._captureGPUFrameTime;
  87994. },
  87995. /**
  87996. * Enable or disable the GPU frame time capture
  87997. */
  87998. set: function (value) {
  87999. var _this = this;
  88000. if (value === this._captureGPUFrameTime) {
  88001. return;
  88002. }
  88003. this._captureGPUFrameTime = value;
  88004. if (value) {
  88005. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  88006. if (!_this._gpuFrameTimeToken) {
  88007. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  88008. }
  88009. });
  88010. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  88011. if (!_this._gpuFrameTimeToken) {
  88012. return;
  88013. }
  88014. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  88015. if (time > -1) {
  88016. _this._gpuFrameTimeToken = null;
  88017. _this._gpuFrameTime.fetchNewFrame();
  88018. _this._gpuFrameTime.addCount(time, true);
  88019. }
  88020. });
  88021. }
  88022. else {
  88023. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  88024. this._onBeginFrameObserver = null;
  88025. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  88026. this._onEndFrameObserver = null;
  88027. }
  88028. },
  88029. enumerable: true,
  88030. configurable: true
  88031. });
  88032. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  88033. /**
  88034. * Gets the perf counter used for shader compilation time
  88035. */
  88036. get: function () {
  88037. return this._shaderCompilationTime;
  88038. },
  88039. enumerable: true,
  88040. configurable: true
  88041. });
  88042. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  88043. /**
  88044. * Gets the shader compilation time capture status
  88045. */
  88046. get: function () {
  88047. return this._captureShaderCompilationTime;
  88048. },
  88049. /**
  88050. * Enable or disable the shader compilation time capture
  88051. */
  88052. set: function (value) {
  88053. var _this = this;
  88054. if (value === this._captureShaderCompilationTime) {
  88055. return;
  88056. }
  88057. this._captureShaderCompilationTime = value;
  88058. if (value) {
  88059. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  88060. _this._shaderCompilationTime.fetchNewFrame();
  88061. _this._shaderCompilationTime.beginMonitoring();
  88062. });
  88063. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  88064. _this._shaderCompilationTime.endMonitoring();
  88065. });
  88066. }
  88067. else {
  88068. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  88069. this._onBeforeShaderCompilationObserver = null;
  88070. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  88071. this._onAfterShaderCompilationObserver = null;
  88072. }
  88073. },
  88074. enumerable: true,
  88075. configurable: true
  88076. });
  88077. EngineInstrumentation.prototype.dispose = function () {
  88078. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  88079. this._onBeginFrameObserver = null;
  88080. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  88081. this._onEndFrameObserver = null;
  88082. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  88083. this._onBeforeShaderCompilationObserver = null;
  88084. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  88085. this._onAfterShaderCompilationObserver = null;
  88086. this.engine = null;
  88087. };
  88088. return EngineInstrumentation;
  88089. }());
  88090. BABYLON.EngineInstrumentation = EngineInstrumentation;
  88091. })(BABYLON || (BABYLON = {}));
  88092. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  88093. var BABYLON;
  88094. (function (BABYLON) {
  88095. /**
  88096. * This class can be used to get instrumentation data from a Babylon engine
  88097. */
  88098. var SceneInstrumentation = /** @class */ (function () {
  88099. function SceneInstrumentation(scene) {
  88100. var _this = this;
  88101. this.scene = scene;
  88102. this._captureActiveMeshesEvaluationTime = false;
  88103. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  88104. this._captureRenderTargetsRenderTime = false;
  88105. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  88106. this._captureFrameTime = false;
  88107. this._frameTime = new BABYLON.PerfCounter();
  88108. this._captureRenderTime = false;
  88109. this._renderTime = new BABYLON.PerfCounter();
  88110. this._captureInterFrameTime = false;
  88111. this._interFrameTime = new BABYLON.PerfCounter();
  88112. this._captureParticlesRenderTime = false;
  88113. this._particlesRenderTime = new BABYLON.PerfCounter();
  88114. this._captureSpritesRenderTime = false;
  88115. this._spritesRenderTime = new BABYLON.PerfCounter();
  88116. this._capturePhysicsTime = false;
  88117. this._physicsTime = new BABYLON.PerfCounter();
  88118. this._captureAnimationsTime = false;
  88119. this._animationsTime = new BABYLON.PerfCounter();
  88120. // Observers
  88121. this._onBeforeActiveMeshesEvaluationObserver = null;
  88122. this._onAfterActiveMeshesEvaluationObserver = null;
  88123. this._onBeforeRenderTargetsRenderObserver = null;
  88124. this._onAfterRenderTargetsRenderObserver = null;
  88125. this._onAfterRenderObserver = null;
  88126. this._onBeforeDrawPhaseObserver = null;
  88127. this._onAfterDrawPhaseObserver = null;
  88128. this._onBeforeAnimationsObserver = null;
  88129. this._onBeforeParticlesRenderingObserver = null;
  88130. this._onAfterParticlesRenderingObserver = null;
  88131. this._onBeforeSpritesRenderingObserver = null;
  88132. this._onAfterSpritesRenderingObserver = null;
  88133. this._onBeforePhysicsObserver = null;
  88134. this._onAfterPhysicsObserver = null;
  88135. this._onAfterAnimationsObserver = null;
  88136. // Before render
  88137. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  88138. if (_this._captureActiveMeshesEvaluationTime) {
  88139. _this._activeMeshesEvaluationTime.fetchNewFrame();
  88140. }
  88141. if (_this._captureRenderTargetsRenderTime) {
  88142. _this._renderTargetsRenderTime.fetchNewFrame();
  88143. }
  88144. if (_this._captureFrameTime) {
  88145. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  88146. _this._frameTime.beginMonitoring();
  88147. }
  88148. if (_this._captureInterFrameTime) {
  88149. _this._interFrameTime.endMonitoring();
  88150. }
  88151. if (_this._captureParticlesRenderTime) {
  88152. _this._particlesRenderTime.fetchNewFrame();
  88153. }
  88154. if (_this._captureSpritesRenderTime) {
  88155. _this._spritesRenderTime.fetchNewFrame();
  88156. }
  88157. if (_this._captureAnimationsTime) {
  88158. _this._animationsTime.beginMonitoring();
  88159. }
  88160. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  88161. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  88162. });
  88163. // After render
  88164. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  88165. if (_this._captureFrameTime) {
  88166. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  88167. _this._frameTime.endMonitoring();
  88168. }
  88169. if (_this._captureRenderTime) {
  88170. _this._renderTime.endMonitoring(false);
  88171. }
  88172. if (_this._captureInterFrameTime) {
  88173. _this._interFrameTime.beginMonitoring();
  88174. }
  88175. });
  88176. }
  88177. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  88178. // Properties
  88179. /**
  88180. * Gets the perf counter used for active meshes evaluation time
  88181. */
  88182. get: function () {
  88183. return this._activeMeshesEvaluationTime;
  88184. },
  88185. enumerable: true,
  88186. configurable: true
  88187. });
  88188. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  88189. /**
  88190. * Gets the active meshes evaluation time capture status
  88191. */
  88192. get: function () {
  88193. return this._captureActiveMeshesEvaluationTime;
  88194. },
  88195. /**
  88196. * Enable or disable the active meshes evaluation time capture
  88197. */
  88198. set: function (value) {
  88199. var _this = this;
  88200. if (value === this._captureActiveMeshesEvaluationTime) {
  88201. return;
  88202. }
  88203. this._captureActiveMeshesEvaluationTime = value;
  88204. if (value) {
  88205. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  88206. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  88207. _this._activeMeshesEvaluationTime.beginMonitoring();
  88208. });
  88209. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  88210. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  88211. _this._activeMeshesEvaluationTime.endMonitoring();
  88212. });
  88213. }
  88214. else {
  88215. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  88216. this._onBeforeActiveMeshesEvaluationObserver = null;
  88217. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  88218. this._onAfterActiveMeshesEvaluationObserver = null;
  88219. }
  88220. },
  88221. enumerable: true,
  88222. configurable: true
  88223. });
  88224. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  88225. /**
  88226. * Gets the perf counter used for render targets render time
  88227. */
  88228. get: function () {
  88229. return this._renderTargetsRenderTime;
  88230. },
  88231. enumerable: true,
  88232. configurable: true
  88233. });
  88234. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  88235. /**
  88236. * Gets the render targets render time capture status
  88237. */
  88238. get: function () {
  88239. return this._captureRenderTargetsRenderTime;
  88240. },
  88241. /**
  88242. * Enable or disable the render targets render time capture
  88243. */
  88244. set: function (value) {
  88245. var _this = this;
  88246. if (value === this._captureRenderTargetsRenderTime) {
  88247. return;
  88248. }
  88249. this._captureRenderTargetsRenderTime = value;
  88250. if (value) {
  88251. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  88252. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  88253. _this._renderTargetsRenderTime.beginMonitoring();
  88254. });
  88255. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  88256. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  88257. _this._renderTargetsRenderTime.endMonitoring(false);
  88258. });
  88259. }
  88260. else {
  88261. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  88262. this._onBeforeRenderTargetsRenderObserver = null;
  88263. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  88264. this._onAfterRenderTargetsRenderObserver = null;
  88265. }
  88266. },
  88267. enumerable: true,
  88268. configurable: true
  88269. });
  88270. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  88271. /**
  88272. * Gets the perf counter used for particles render time
  88273. */
  88274. get: function () {
  88275. return this._particlesRenderTime;
  88276. },
  88277. enumerable: true,
  88278. configurable: true
  88279. });
  88280. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  88281. /**
  88282. * Gets the particles render time capture status
  88283. */
  88284. get: function () {
  88285. return this._captureParticlesRenderTime;
  88286. },
  88287. /**
  88288. * Enable or disable the particles render time capture
  88289. */
  88290. set: function (value) {
  88291. var _this = this;
  88292. if (value === this._captureParticlesRenderTime) {
  88293. return;
  88294. }
  88295. this._captureParticlesRenderTime = value;
  88296. if (value) {
  88297. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  88298. BABYLON.Tools.StartPerformanceCounter("Particles");
  88299. _this._particlesRenderTime.beginMonitoring();
  88300. });
  88301. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  88302. BABYLON.Tools.EndPerformanceCounter("Particles");
  88303. _this._particlesRenderTime.endMonitoring(false);
  88304. });
  88305. }
  88306. else {
  88307. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  88308. this._onBeforeParticlesRenderingObserver = null;
  88309. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  88310. this._onAfterParticlesRenderingObserver = null;
  88311. }
  88312. },
  88313. enumerable: true,
  88314. configurable: true
  88315. });
  88316. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  88317. /**
  88318. * Gets the perf counter used for sprites render time
  88319. */
  88320. get: function () {
  88321. return this._spritesRenderTime;
  88322. },
  88323. enumerable: true,
  88324. configurable: true
  88325. });
  88326. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  88327. /**
  88328. * Gets the sprites render time capture status
  88329. */
  88330. get: function () {
  88331. return this._captureSpritesRenderTime;
  88332. },
  88333. /**
  88334. * Enable or disable the sprites render time capture
  88335. */
  88336. set: function (value) {
  88337. var _this = this;
  88338. if (value === this._captureSpritesRenderTime) {
  88339. return;
  88340. }
  88341. this._captureSpritesRenderTime = value;
  88342. if (value) {
  88343. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  88344. BABYLON.Tools.StartPerformanceCounter("Sprites");
  88345. _this._spritesRenderTime.beginMonitoring();
  88346. });
  88347. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  88348. BABYLON.Tools.EndPerformanceCounter("Sprites");
  88349. _this._spritesRenderTime.endMonitoring(false);
  88350. });
  88351. }
  88352. else {
  88353. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  88354. this._onBeforeSpritesRenderingObserver = null;
  88355. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  88356. this._onAfterSpritesRenderingObserver = null;
  88357. }
  88358. },
  88359. enumerable: true,
  88360. configurable: true
  88361. });
  88362. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  88363. /**
  88364. * Gets the perf counter used for physics time
  88365. */
  88366. get: function () {
  88367. return this._physicsTime;
  88368. },
  88369. enumerable: true,
  88370. configurable: true
  88371. });
  88372. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  88373. /**
  88374. * Gets the physics time capture status
  88375. */
  88376. get: function () {
  88377. return this._capturePhysicsTime;
  88378. },
  88379. /**
  88380. * Enable or disable the physics time capture
  88381. */
  88382. set: function (value) {
  88383. var _this = this;
  88384. if (value === this._capturePhysicsTime) {
  88385. return;
  88386. }
  88387. this._capturePhysicsTime = value;
  88388. if (value) {
  88389. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  88390. BABYLON.Tools.StartPerformanceCounter("Physics");
  88391. _this._physicsTime.beginMonitoring();
  88392. });
  88393. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  88394. BABYLON.Tools.EndPerformanceCounter("Physics");
  88395. _this._physicsTime.endMonitoring();
  88396. });
  88397. }
  88398. else {
  88399. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  88400. this._onBeforePhysicsObserver = null;
  88401. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  88402. this._onAfterPhysicsObserver = null;
  88403. }
  88404. },
  88405. enumerable: true,
  88406. configurable: true
  88407. });
  88408. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  88409. /**
  88410. * Gets the perf counter used for animations time
  88411. */
  88412. get: function () {
  88413. return this._animationsTime;
  88414. },
  88415. enumerable: true,
  88416. configurable: true
  88417. });
  88418. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  88419. /**
  88420. * Gets the animations time capture status
  88421. */
  88422. get: function () {
  88423. return this._captureAnimationsTime;
  88424. },
  88425. /**
  88426. * Enable or disable the animations time capture
  88427. */
  88428. set: function (value) {
  88429. var _this = this;
  88430. if (value === this._captureAnimationsTime) {
  88431. return;
  88432. }
  88433. this._captureAnimationsTime = value;
  88434. if (value) {
  88435. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  88436. _this._animationsTime.endMonitoring();
  88437. });
  88438. }
  88439. else {
  88440. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  88441. this._onAfterAnimationsObserver = null;
  88442. }
  88443. },
  88444. enumerable: true,
  88445. configurable: true
  88446. });
  88447. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  88448. /**
  88449. * Gets the perf counter used for frame time capture
  88450. */
  88451. get: function () {
  88452. return this._frameTime;
  88453. },
  88454. enumerable: true,
  88455. configurable: true
  88456. });
  88457. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  88458. /**
  88459. * Gets the frame time capture status
  88460. */
  88461. get: function () {
  88462. return this._captureFrameTime;
  88463. },
  88464. /**
  88465. * Enable or disable the frame time capture
  88466. */
  88467. set: function (value) {
  88468. this._captureFrameTime = value;
  88469. },
  88470. enumerable: true,
  88471. configurable: true
  88472. });
  88473. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  88474. /**
  88475. * Gets the perf counter used for inter-frames time capture
  88476. */
  88477. get: function () {
  88478. return this._interFrameTime;
  88479. },
  88480. enumerable: true,
  88481. configurable: true
  88482. });
  88483. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  88484. /**
  88485. * Gets the inter-frames time capture status
  88486. */
  88487. get: function () {
  88488. return this._captureInterFrameTime;
  88489. },
  88490. /**
  88491. * Enable or disable the inter-frames time capture
  88492. */
  88493. set: function (value) {
  88494. this._captureInterFrameTime = value;
  88495. },
  88496. enumerable: true,
  88497. configurable: true
  88498. });
  88499. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  88500. /**
  88501. * Gets the perf counter used for render time capture
  88502. */
  88503. get: function () {
  88504. return this._renderTime;
  88505. },
  88506. enumerable: true,
  88507. configurable: true
  88508. });
  88509. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  88510. /**
  88511. * Gets the render time capture status
  88512. */
  88513. get: function () {
  88514. return this._captureRenderTime;
  88515. },
  88516. /**
  88517. * Enable or disable the render time capture
  88518. */
  88519. set: function (value) {
  88520. var _this = this;
  88521. if (value === this._captureRenderTime) {
  88522. return;
  88523. }
  88524. this._captureRenderTime = value;
  88525. if (value) {
  88526. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  88527. _this._renderTime.beginMonitoring();
  88528. BABYLON.Tools.StartPerformanceCounter("Main render");
  88529. });
  88530. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  88531. _this._renderTime.endMonitoring(false);
  88532. BABYLON.Tools.EndPerformanceCounter("Main render");
  88533. });
  88534. }
  88535. else {
  88536. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  88537. this._onBeforeDrawPhaseObserver = null;
  88538. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  88539. this._onAfterDrawPhaseObserver = null;
  88540. }
  88541. },
  88542. enumerable: true,
  88543. configurable: true
  88544. });
  88545. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  88546. /**
  88547. * Gets the perf counter used for draw calls
  88548. */
  88549. get: function () {
  88550. return this.scene.getEngine()._drawCalls;
  88551. },
  88552. enumerable: true,
  88553. configurable: true
  88554. });
  88555. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  88556. /**
  88557. * Gets the perf counter used for texture collisions
  88558. */
  88559. get: function () {
  88560. return this.scene.getEngine()._textureCollisions;
  88561. },
  88562. enumerable: true,
  88563. configurable: true
  88564. });
  88565. SceneInstrumentation.prototype.dispose = function () {
  88566. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  88567. this._onAfterRenderObserver = null;
  88568. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  88569. this._onBeforeActiveMeshesEvaluationObserver = null;
  88570. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  88571. this._onAfterActiveMeshesEvaluationObserver = null;
  88572. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  88573. this._onBeforeRenderTargetsRenderObserver = null;
  88574. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  88575. this._onAfterRenderTargetsRenderObserver = null;
  88576. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  88577. this._onBeforeAnimationsObserver = null;
  88578. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  88579. this._onBeforeParticlesRenderingObserver = null;
  88580. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  88581. this._onAfterParticlesRenderingObserver = null;
  88582. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  88583. this._onBeforeSpritesRenderingObserver = null;
  88584. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  88585. this._onAfterSpritesRenderingObserver = null;
  88586. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  88587. this._onBeforeDrawPhaseObserver = null;
  88588. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  88589. this._onAfterDrawPhaseObserver = null;
  88590. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  88591. this._onBeforePhysicsObserver = null;
  88592. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  88593. this._onAfterPhysicsObserver = null;
  88594. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  88595. this._onAfterAnimationsObserver = null;
  88596. this.scene = null;
  88597. };
  88598. return SceneInstrumentation;
  88599. }());
  88600. BABYLON.SceneInstrumentation = SceneInstrumentation;
  88601. })(BABYLON || (BABYLON = {}));
  88602. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  88603. var BABYLON;
  88604. (function (BABYLON) {
  88605. var _TimeToken = /** @class */ (function () {
  88606. function _TimeToken() {
  88607. this._timeElapsedQueryEnded = false;
  88608. }
  88609. return _TimeToken;
  88610. }());
  88611. BABYLON._TimeToken = _TimeToken;
  88612. })(BABYLON || (BABYLON = {}));
  88613. //# sourceMappingURL=babylon.timeToken.js.map
  88614. var BABYLON;
  88615. (function (BABYLON) {
  88616. /**
  88617. * Background material defines definition.
  88618. * @ignore Mainly internal Use
  88619. */
  88620. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  88621. __extends(BackgroundMaterialDefines, _super);
  88622. /**
  88623. * Constructor of the defines.
  88624. */
  88625. function BackgroundMaterialDefines() {
  88626. var _this = _super.call(this) || this;
  88627. /**
  88628. * True if the diffuse texture is in use.
  88629. */
  88630. _this.DIFFUSE = false;
  88631. /**
  88632. * The direct UV channel to use.
  88633. */
  88634. _this.DIFFUSEDIRECTUV = 0;
  88635. /**
  88636. * True if the diffuse texture is in gamma space.
  88637. */
  88638. _this.GAMMADIFFUSE = false;
  88639. /**
  88640. * True if the diffuse texture has opacity in the alpha channel.
  88641. */
  88642. _this.DIFFUSEHASALPHA = false;
  88643. /**
  88644. * True if you want the material to fade to transparent at grazing angle.
  88645. */
  88646. _this.OPACITYFRESNEL = false;
  88647. /**
  88648. * True if an extra blur needs to be added in the reflection.
  88649. */
  88650. _this.REFLECTIONBLUR = false;
  88651. /**
  88652. * True if you want the material to fade to reflection at grazing angle.
  88653. */
  88654. _this.REFLECTIONFRESNEL = false;
  88655. /**
  88656. * True if you want the material to falloff as far as you move away from the scene center.
  88657. */
  88658. _this.REFLECTIONFALLOFF = false;
  88659. /**
  88660. * False if the current Webgl implementation does not support the texture lod extension.
  88661. */
  88662. _this.TEXTURELODSUPPORT = false;
  88663. /**
  88664. * True to ensure the data are premultiplied.
  88665. */
  88666. _this.PREMULTIPLYALPHA = false;
  88667. /**
  88668. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  88669. */
  88670. _this.USERGBCOLOR = false;
  88671. /**
  88672. * True to add noise in order to reduce the banding effect.
  88673. */
  88674. _this.NOISE = false;
  88675. /**
  88676. * is the reflection texture in BGR color scheme?
  88677. * Mainly used to solve a bug in ios10 video tag
  88678. */
  88679. _this.REFLECTIONBGR = false;
  88680. _this.IMAGEPROCESSING = false;
  88681. _this.VIGNETTE = false;
  88682. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  88683. _this.VIGNETTEBLENDMODEOPAQUE = false;
  88684. _this.TONEMAPPING = false;
  88685. _this.CONTRAST = false;
  88686. _this.COLORCURVES = false;
  88687. _this.COLORGRADING = false;
  88688. _this.COLORGRADING3D = false;
  88689. _this.SAMPLER3DGREENDEPTH = false;
  88690. _this.SAMPLER3DBGRMAP = false;
  88691. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  88692. _this.EXPOSURE = false;
  88693. // Reflection.
  88694. _this.REFLECTION = false;
  88695. _this.REFLECTIONMAP_3D = false;
  88696. _this.REFLECTIONMAP_SPHERICAL = false;
  88697. _this.REFLECTIONMAP_PLANAR = false;
  88698. _this.REFLECTIONMAP_CUBIC = false;
  88699. _this.REFLECTIONMAP_PROJECTION = false;
  88700. _this.REFLECTIONMAP_SKYBOX = false;
  88701. _this.REFLECTIONMAP_EXPLICIT = false;
  88702. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  88703. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  88704. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  88705. _this.INVERTCUBICMAP = false;
  88706. _this.REFLECTIONMAP_OPPOSITEZ = false;
  88707. _this.LODINREFLECTIONALPHA = false;
  88708. _this.GAMMAREFLECTION = false;
  88709. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  88710. // Default BJS.
  88711. _this.MAINUV1 = false;
  88712. _this.MAINUV2 = false;
  88713. _this.UV1 = false;
  88714. _this.UV2 = false;
  88715. _this.CLIPPLANE = false;
  88716. _this.POINTSIZE = false;
  88717. _this.FOG = false;
  88718. _this.NORMAL = false;
  88719. _this.NUM_BONE_INFLUENCERS = 0;
  88720. _this.BonesPerMesh = 0;
  88721. _this.INSTANCES = false;
  88722. _this.SHADOWFLOAT = false;
  88723. _this.rebuild();
  88724. return _this;
  88725. }
  88726. return BackgroundMaterialDefines;
  88727. }(BABYLON.MaterialDefines));
  88728. /**
  88729. * Background material used to create an efficient environement around your scene.
  88730. */
  88731. var BackgroundMaterial = /** @class */ (function (_super) {
  88732. __extends(BackgroundMaterial, _super);
  88733. /**
  88734. * Instantiates a Background Material in the given scene
  88735. * @param name The friendly name of the material
  88736. * @param scene The scene to add the material to
  88737. */
  88738. function BackgroundMaterial(name, scene) {
  88739. var _this = _super.call(this, name, scene) || this;
  88740. /**
  88741. * Key light Color (multiply against the R channel of the environement texture)
  88742. */
  88743. _this.primaryColor = BABYLON.Color3.White();
  88744. /**
  88745. * Key light Level (allowing HDR output of the background)
  88746. */
  88747. _this.primaryLevel = 1;
  88748. /**
  88749. * Secondary light Color (multiply against the G channel of the environement texture)
  88750. */
  88751. _this.secondaryColor = BABYLON.Color3.Gray();
  88752. /**
  88753. * Secondary light Level (allowing HDR output of the background)
  88754. */
  88755. _this.secondaryLevel = 1;
  88756. /**
  88757. * Tertiary light Color (multiply against the B channel of the environement texture)
  88758. */
  88759. _this.tertiaryColor = BABYLON.Color3.Black();
  88760. /**
  88761. * Tertiary light Level (allowing HDR output of the background)
  88762. */
  88763. _this.tertiaryLevel = 1;
  88764. /**
  88765. * Reflection Texture used in the material.
  88766. * Should be author in a specific way for the best result (refer to the documentation).
  88767. */
  88768. _this.reflectionTexture = null;
  88769. /**
  88770. * Reflection Texture level of blur.
  88771. *
  88772. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  88773. * texture twice.
  88774. */
  88775. _this.reflectionBlur = 0;
  88776. /**
  88777. * Diffuse Texture used in the material.
  88778. * Should be author in a specific way for the best result (refer to the documentation).
  88779. */
  88780. _this.diffuseTexture = null;
  88781. _this._shadowLights = null;
  88782. /**
  88783. * Specify the list of lights casting shadow on the material.
  88784. * All scene shadow lights will be included if null.
  88785. */
  88786. _this.shadowLights = null;
  88787. /**
  88788. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  88789. * soft lighting on the background.
  88790. */
  88791. _this.shadowBlurScale = 1;
  88792. /**
  88793. * Helps adjusting the shadow to a softer level if required.
  88794. * 0 means black shadows and 1 means no shadows.
  88795. */
  88796. _this.shadowLevel = 0;
  88797. /**
  88798. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  88799. * It is usually zero but might be interesting to modify according to your setup.
  88800. */
  88801. _this.sceneCenter = BABYLON.Vector3.Zero();
  88802. /**
  88803. * This helps specifying that the material is falling off to the sky box at grazing angle.
  88804. * This helps ensuring a nice transition when the camera goes under the ground.
  88805. */
  88806. _this.opacityFresnel = true;
  88807. /**
  88808. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  88809. * This helps adding a mirror texture on the ground.
  88810. */
  88811. _this.reflectionFresnel = false;
  88812. /**
  88813. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  88814. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  88815. */
  88816. _this.reflectionFalloffDistance = 0.0;
  88817. /**
  88818. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  88819. */
  88820. _this.reflectionAmount = 1.0;
  88821. /**
  88822. * This specifies the weight of the reflection at grazing angle.
  88823. */
  88824. _this.reflectionReflectance0 = 0.05;
  88825. /**
  88826. * This specifies the weight of the reflection at a perpendicular point of view.
  88827. */
  88828. _this.reflectionReflectance90 = 0.5;
  88829. /**
  88830. * Helps to directly use the maps channels instead of their level.
  88831. */
  88832. _this.useRGBColor = true;
  88833. /**
  88834. * This helps reducing the banding effect that could occur on the background.
  88835. */
  88836. _this.enableNoise = false;
  88837. _this._fovMultiplier = 1.0;
  88838. /**
  88839. * Enable the FOV adjustment feature controlled by fovMultiplier.
  88840. * @type {boolean}
  88841. */
  88842. _this.useEquirectangularFOV = false;
  88843. _this._maxSimultaneousLights = 4;
  88844. /**
  88845. * Number of Simultaneous lights allowed on the material.
  88846. */
  88847. _this.maxSimultaneousLights = 4;
  88848. /**
  88849. * Keep track of the image processing observer to allow dispose and replace.
  88850. */
  88851. _this._imageProcessingObserver = null;
  88852. /**
  88853. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  88854. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  88855. */
  88856. _this.switchToBGR = false;
  88857. // Temp values kept as cache in the material.
  88858. _this._renderTargets = new BABYLON.SmartArray(16);
  88859. _this._reflectionControls = BABYLON.Vector4.Zero();
  88860. // Setup the default processing configuration to the scene.
  88861. _this._attachImageProcessingConfiguration(null);
  88862. _this.getRenderTargetTextures = function () {
  88863. _this._renderTargets.reset();
  88864. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  88865. _this._renderTargets.push(_this._diffuseTexture);
  88866. }
  88867. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  88868. _this._renderTargets.push(_this._reflectionTexture);
  88869. }
  88870. return _this._renderTargets;
  88871. };
  88872. return _this;
  88873. }
  88874. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  88875. /**
  88876. * Sets the reflection reflectance fresnel values according to the default standard
  88877. * empirically know to work well :-)
  88878. */
  88879. set: function (value) {
  88880. var reflectionWeight = value;
  88881. if (reflectionWeight < 0.5) {
  88882. reflectionWeight = reflectionWeight * 2.0;
  88883. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  88884. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  88885. }
  88886. else {
  88887. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  88888. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  88889. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  88890. }
  88891. },
  88892. enumerable: true,
  88893. configurable: true
  88894. });
  88895. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  88896. /**
  88897. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  88898. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  88899. * Recommended to be keep at 1.0 except for special cases.
  88900. */
  88901. get: function () {
  88902. return this._fovMultiplier;
  88903. },
  88904. set: function (value) {
  88905. if (isNaN(value)) {
  88906. value = 1.0;
  88907. }
  88908. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  88909. },
  88910. enumerable: true,
  88911. configurable: true
  88912. });
  88913. /**
  88914. * Attaches a new image processing configuration to the PBR Material.
  88915. * @param configuration (if null the scene configuration will be use)
  88916. */
  88917. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  88918. var _this = this;
  88919. if (configuration === this._imageProcessingConfiguration) {
  88920. return;
  88921. }
  88922. // Detaches observer.
  88923. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  88924. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  88925. }
  88926. // Pick the scene configuration if needed.
  88927. if (!configuration) {
  88928. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  88929. }
  88930. else {
  88931. this._imageProcessingConfiguration = configuration;
  88932. }
  88933. // Attaches observer.
  88934. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  88935. _this._markAllSubMeshesAsImageProcessingDirty();
  88936. });
  88937. };
  88938. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  88939. /**
  88940. * Gets the image processing configuration used either in this material.
  88941. */
  88942. get: function () {
  88943. return this._imageProcessingConfiguration;
  88944. },
  88945. /**
  88946. * Sets the Default image processing configuration used either in the this material.
  88947. *
  88948. * If sets to null, the scene one is in use.
  88949. */
  88950. set: function (value) {
  88951. this._attachImageProcessingConfiguration(value);
  88952. // Ensure the effect will be rebuilt.
  88953. this._markAllSubMeshesAsTexturesDirty();
  88954. },
  88955. enumerable: true,
  88956. configurable: true
  88957. });
  88958. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  88959. /**
  88960. * Gets wether the color curves effect is enabled.
  88961. */
  88962. get: function () {
  88963. return this.imageProcessingConfiguration.colorCurvesEnabled;
  88964. },
  88965. /**
  88966. * Sets wether the color curves effect is enabled.
  88967. */
  88968. set: function (value) {
  88969. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  88970. },
  88971. enumerable: true,
  88972. configurable: true
  88973. });
  88974. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  88975. /**
  88976. * Gets wether the color grading effect is enabled.
  88977. */
  88978. get: function () {
  88979. return this.imageProcessingConfiguration.colorGradingEnabled;
  88980. },
  88981. /**
  88982. * Gets wether the color grading effect is enabled.
  88983. */
  88984. set: function (value) {
  88985. this.imageProcessingConfiguration.colorGradingEnabled = value;
  88986. },
  88987. enumerable: true,
  88988. configurable: true
  88989. });
  88990. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  88991. /**
  88992. * Gets wether tonemapping is enabled or not.
  88993. */
  88994. get: function () {
  88995. return this._imageProcessingConfiguration.toneMappingEnabled;
  88996. },
  88997. /**
  88998. * Sets wether tonemapping is enabled or not
  88999. */
  89000. set: function (value) {
  89001. this._imageProcessingConfiguration.toneMappingEnabled = value;
  89002. },
  89003. enumerable: true,
  89004. configurable: true
  89005. });
  89006. ;
  89007. ;
  89008. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  89009. /**
  89010. * The camera exposure used on this material.
  89011. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  89012. * This corresponds to a photographic exposure.
  89013. */
  89014. get: function () {
  89015. return this._imageProcessingConfiguration.exposure;
  89016. },
  89017. /**
  89018. * The camera exposure used on this material.
  89019. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  89020. * This corresponds to a photographic exposure.
  89021. */
  89022. set: function (value) {
  89023. this._imageProcessingConfiguration.exposure = value;
  89024. },
  89025. enumerable: true,
  89026. configurable: true
  89027. });
  89028. ;
  89029. ;
  89030. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  89031. /**
  89032. * Gets The camera contrast used on this material.
  89033. */
  89034. get: function () {
  89035. return this._imageProcessingConfiguration.contrast;
  89036. },
  89037. /**
  89038. * Sets The camera contrast used on this material.
  89039. */
  89040. set: function (value) {
  89041. this._imageProcessingConfiguration.contrast = value;
  89042. },
  89043. enumerable: true,
  89044. configurable: true
  89045. });
  89046. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  89047. /**
  89048. * Gets the Color Grading 2D Lookup Texture.
  89049. */
  89050. get: function () {
  89051. return this._imageProcessingConfiguration.colorGradingTexture;
  89052. },
  89053. /**
  89054. * Sets the Color Grading 2D Lookup Texture.
  89055. */
  89056. set: function (value) {
  89057. this.imageProcessingConfiguration.colorGradingTexture = value;
  89058. },
  89059. enumerable: true,
  89060. configurable: true
  89061. });
  89062. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  89063. /**
  89064. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  89065. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  89066. * 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;
  89067. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  89068. */
  89069. get: function () {
  89070. return this.imageProcessingConfiguration.colorCurves;
  89071. },
  89072. /**
  89073. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  89074. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  89075. * 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;
  89076. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  89077. */
  89078. set: function (value) {
  89079. this.imageProcessingConfiguration.colorCurves = value;
  89080. },
  89081. enumerable: true,
  89082. configurable: true
  89083. });
  89084. /**
  89085. * The entire material has been created in order to prevent overdraw.
  89086. * @returns false
  89087. */
  89088. BackgroundMaterial.prototype.needAlphaTesting = function () {
  89089. return true;
  89090. };
  89091. /**
  89092. * The entire material has been created in order to prevent overdraw.
  89093. * @returns true if blending is enable
  89094. */
  89095. BackgroundMaterial.prototype.needAlphaBlending = function () {
  89096. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  89097. };
  89098. /**
  89099. * Checks wether the material is ready to be rendered for a given mesh.
  89100. * @param mesh The mesh to render
  89101. * @param subMesh The submesh to check against
  89102. * @param useInstances Specify wether or not the material is used with instances
  89103. * @returns true if all the dependencies are ready (Textures, Effects...)
  89104. */
  89105. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  89106. var _this = this;
  89107. if (useInstances === void 0) { useInstances = false; }
  89108. if (subMesh.effect && this.isFrozen) {
  89109. if (this._wasPreviouslyReady) {
  89110. return true;
  89111. }
  89112. }
  89113. if (!subMesh._materialDefines) {
  89114. subMesh._materialDefines = new BackgroundMaterialDefines();
  89115. }
  89116. var scene = this.getScene();
  89117. var defines = subMesh._materialDefines;
  89118. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  89119. if (defines._renderId === scene.getRenderId()) {
  89120. return true;
  89121. }
  89122. }
  89123. var engine = scene.getEngine();
  89124. // Lights
  89125. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  89126. defines._needNormals = true;
  89127. // Textures
  89128. if (defines._areTexturesDirty) {
  89129. defines._needUVs = false;
  89130. if (scene.texturesEnabled) {
  89131. if (scene.getEngine().getCaps().textureLOD) {
  89132. defines.TEXTURELODSUPPORT = true;
  89133. }
  89134. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  89135. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  89136. return false;
  89137. }
  89138. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  89139. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  89140. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  89141. defines.OPACITYFRESNEL = this._opacityFresnel;
  89142. }
  89143. else {
  89144. defines.DIFFUSE = false;
  89145. defines.DIFFUSEHASALPHA = false;
  89146. defines.GAMMADIFFUSE = false;
  89147. defines.OPACITYFRESNEL = false;
  89148. }
  89149. var reflectionTexture = this._reflectionTexture;
  89150. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  89151. if (!reflectionTexture.isReadyOrNotBlocking()) {
  89152. return false;
  89153. }
  89154. defines.REFLECTION = true;
  89155. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  89156. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  89157. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  89158. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  89159. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  89160. defines.REFLECTIONBGR = this.switchToBGR;
  89161. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  89162. defines.INVERTCUBICMAP = true;
  89163. }
  89164. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  89165. switch (reflectionTexture.coordinatesMode) {
  89166. case BABYLON.Texture.CUBIC_MODE:
  89167. case BABYLON.Texture.INVCUBIC_MODE:
  89168. defines.REFLECTIONMAP_CUBIC = true;
  89169. break;
  89170. case BABYLON.Texture.EXPLICIT_MODE:
  89171. defines.REFLECTIONMAP_EXPLICIT = true;
  89172. break;
  89173. case BABYLON.Texture.PLANAR_MODE:
  89174. defines.REFLECTIONMAP_PLANAR = true;
  89175. break;
  89176. case BABYLON.Texture.PROJECTION_MODE:
  89177. defines.REFLECTIONMAP_PROJECTION = true;
  89178. break;
  89179. case BABYLON.Texture.SKYBOX_MODE:
  89180. defines.REFLECTIONMAP_SKYBOX = true;
  89181. break;
  89182. case BABYLON.Texture.SPHERICAL_MODE:
  89183. defines.REFLECTIONMAP_SPHERICAL = true;
  89184. break;
  89185. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  89186. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  89187. break;
  89188. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  89189. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  89190. break;
  89191. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  89192. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  89193. break;
  89194. }
  89195. if (this.reflectionFresnel) {
  89196. defines.REFLECTIONFRESNEL = true;
  89197. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  89198. this._reflectionControls.x = this.reflectionAmount;
  89199. this._reflectionControls.y = this.reflectionReflectance0;
  89200. this._reflectionControls.z = this.reflectionReflectance90;
  89201. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  89202. }
  89203. else {
  89204. defines.REFLECTIONFRESNEL = false;
  89205. defines.REFLECTIONFALLOFF = false;
  89206. }
  89207. }
  89208. else {
  89209. defines.REFLECTION = false;
  89210. defines.REFLECTIONFALLOFF = false;
  89211. defines.REFLECTIONBLUR = false;
  89212. defines.REFLECTIONMAP_3D = false;
  89213. defines.REFLECTIONMAP_SPHERICAL = false;
  89214. defines.REFLECTIONMAP_PLANAR = false;
  89215. defines.REFLECTIONMAP_CUBIC = false;
  89216. defines.REFLECTIONMAP_PROJECTION = false;
  89217. defines.REFLECTIONMAP_SKYBOX = false;
  89218. defines.REFLECTIONMAP_EXPLICIT = false;
  89219. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  89220. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  89221. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  89222. defines.INVERTCUBICMAP = false;
  89223. defines.REFLECTIONMAP_OPPOSITEZ = false;
  89224. defines.LODINREFLECTIONALPHA = false;
  89225. defines.GAMMAREFLECTION = false;
  89226. }
  89227. }
  89228. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  89229. defines.USERGBCOLOR = this._useRGBColor;
  89230. defines.NOISE = this._enableNoise;
  89231. }
  89232. if (defines._areImageProcessingDirty) {
  89233. if (!this._imageProcessingConfiguration.isReady()) {
  89234. return false;
  89235. }
  89236. this._imageProcessingConfiguration.prepareDefines(defines);
  89237. }
  89238. // Misc.
  89239. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  89240. // Values that need to be evaluated on every frame
  89241. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  89242. // Attribs
  89243. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  89244. if (mesh) {
  89245. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  89246. mesh.createNormals(true);
  89247. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  89248. }
  89249. }
  89250. }
  89251. // Get correct effect
  89252. if (defines.isDirty) {
  89253. defines.markAsProcessed();
  89254. scene.resetCachedMaterial();
  89255. // Fallbacks
  89256. var fallbacks = new BABYLON.EffectFallbacks();
  89257. if (defines.FOG) {
  89258. fallbacks.addFallback(0, "FOG");
  89259. }
  89260. if (defines.POINTSIZE) {
  89261. fallbacks.addFallback(1, "POINTSIZE");
  89262. }
  89263. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  89264. if (defines.NUM_BONE_INFLUENCERS > 0) {
  89265. fallbacks.addCPUSkinningFallback(0, mesh);
  89266. }
  89267. //Attributes
  89268. var attribs = [BABYLON.VertexBuffer.PositionKind];
  89269. if (defines.NORMAL) {
  89270. attribs.push(BABYLON.VertexBuffer.NormalKind);
  89271. }
  89272. if (defines.UV1) {
  89273. attribs.push(BABYLON.VertexBuffer.UVKind);
  89274. }
  89275. if (defines.UV2) {
  89276. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  89277. }
  89278. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  89279. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  89280. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  89281. "vFogInfos", "vFogColor", "pointSize",
  89282. "vClipPlane", "mBones",
  89283. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  89284. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  89285. "shadowLevel", "alpha",
  89286. "vBackgroundCenter", "vReflectionControl",
  89287. "vDiffuseInfos", "diffuseMatrix",
  89288. ];
  89289. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  89290. var uniformBuffers = ["Material", "Scene"];
  89291. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  89292. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  89293. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  89294. uniformsNames: uniforms,
  89295. uniformBuffersNames: uniformBuffers,
  89296. samplers: samplers,
  89297. defines: defines,
  89298. maxSimultaneousLights: this._maxSimultaneousLights
  89299. });
  89300. var onCompiled = function (effect) {
  89301. if (_this.onCompiled) {
  89302. _this.onCompiled(effect);
  89303. }
  89304. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  89305. };
  89306. var join = defines.toString();
  89307. subMesh.setEffect(scene.getEngine().createEffect("background", {
  89308. attributes: attribs,
  89309. uniformsNames: uniforms,
  89310. uniformBuffersNames: uniformBuffers,
  89311. samplers: samplers,
  89312. defines: join,
  89313. fallbacks: fallbacks,
  89314. onCompiled: onCompiled,
  89315. onError: this.onError,
  89316. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  89317. }, engine), defines);
  89318. this.buildUniformLayout();
  89319. }
  89320. if (!subMesh.effect || !subMesh.effect.isReady()) {
  89321. return false;
  89322. }
  89323. defines._renderId = scene.getRenderId();
  89324. this._wasPreviouslyReady = true;
  89325. return true;
  89326. };
  89327. /**
  89328. * Build the uniform buffer used in the material.
  89329. */
  89330. BackgroundMaterial.prototype.buildUniformLayout = function () {
  89331. // Order is important !
  89332. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  89333. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  89334. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  89335. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  89336. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  89337. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  89338. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  89339. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  89340. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  89341. this._uniformBuffer.addUniform("pointSize", 1);
  89342. this._uniformBuffer.addUniform("shadowLevel", 1);
  89343. this._uniformBuffer.addUniform("alpha", 1);
  89344. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  89345. this._uniformBuffer.addUniform("vReflectionControl", 4);
  89346. this._uniformBuffer.create();
  89347. };
  89348. /**
  89349. * Unbind the material.
  89350. */
  89351. BackgroundMaterial.prototype.unbind = function () {
  89352. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  89353. this._uniformBuffer.setTexture("diffuseSampler", null);
  89354. }
  89355. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  89356. this._uniformBuffer.setTexture("reflectionSampler", null);
  89357. }
  89358. _super.prototype.unbind.call(this);
  89359. };
  89360. /**
  89361. * Bind only the world matrix to the material.
  89362. * @param world The world matrix to bind.
  89363. */
  89364. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  89365. this._activeEffect.setMatrix("world", world);
  89366. };
  89367. /**
  89368. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  89369. * @param world The world matrix to bind.
  89370. * @param subMesh The submesh to bind for.
  89371. */
  89372. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  89373. var scene = this.getScene();
  89374. var defines = subMesh._materialDefines;
  89375. if (!defines) {
  89376. return;
  89377. }
  89378. var effect = subMesh.effect;
  89379. if (!effect) {
  89380. return;
  89381. }
  89382. this._activeEffect = effect;
  89383. // Matrices
  89384. this.bindOnlyWorldMatrix(world);
  89385. // Bones
  89386. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  89387. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  89388. if (mustRebind) {
  89389. this._uniformBuffer.bindToEffect(effect, "Material");
  89390. this.bindViewProjection(effect);
  89391. var reflectionTexture = this._reflectionTexture;
  89392. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  89393. // Texture uniforms
  89394. if (scene.texturesEnabled) {
  89395. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  89396. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  89397. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  89398. }
  89399. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  89400. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  89401. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  89402. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  89403. }
  89404. }
  89405. if (this.shadowLevel > 0) {
  89406. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  89407. }
  89408. this._uniformBuffer.updateFloat("alpha", this.alpha);
  89409. // Point size
  89410. if (this.pointsCloud) {
  89411. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  89412. }
  89413. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  89414. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  89415. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  89416. }
  89417. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  89418. // Textures
  89419. if (scene.texturesEnabled) {
  89420. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  89421. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  89422. }
  89423. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  89424. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  89425. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  89426. }
  89427. else if (!defines.REFLECTIONBLUR) {
  89428. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  89429. }
  89430. else {
  89431. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  89432. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  89433. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  89434. }
  89435. if (defines.REFLECTIONFRESNEL) {
  89436. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  89437. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  89438. }
  89439. }
  89440. }
  89441. // Clip plane
  89442. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  89443. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  89444. }
  89445. if (mustRebind || !this.isFrozen) {
  89446. if (scene.lightsEnabled) {
  89447. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  89448. }
  89449. // View
  89450. this.bindView(effect);
  89451. // Fog
  89452. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  89453. // image processing
  89454. this._imageProcessingConfiguration.bind(this._activeEffect);
  89455. }
  89456. this._uniformBuffer.update();
  89457. this._afterBind(mesh);
  89458. };
  89459. /**
  89460. * Dispose the material.
  89461. * @param forceDisposeEffect Force disposal of the associated effect.
  89462. * @param forceDisposeTextures Force disposal of the associated textures.
  89463. */
  89464. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  89465. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  89466. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  89467. if (forceDisposeTextures) {
  89468. if (this.diffuseTexture) {
  89469. this.diffuseTexture.dispose();
  89470. }
  89471. if (this.reflectionTexture) {
  89472. this.reflectionTexture.dispose();
  89473. }
  89474. }
  89475. this._renderTargets.dispose();
  89476. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  89477. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  89478. }
  89479. _super.prototype.dispose.call(this, forceDisposeEffect);
  89480. };
  89481. /**
  89482. * Clones the material.
  89483. * @param name The cloned name.
  89484. * @returns The cloned material.
  89485. */
  89486. BackgroundMaterial.prototype.clone = function (name) {
  89487. var _this = this;
  89488. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  89489. };
  89490. /**
  89491. * Serializes the current material to its JSON representation.
  89492. * @returns The JSON representation.
  89493. */
  89494. BackgroundMaterial.prototype.serialize = function () {
  89495. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  89496. serializationObject.customType = "BABYLON.BackgroundMaterial";
  89497. return serializationObject;
  89498. };
  89499. /**
  89500. * Gets the class name of the material
  89501. * @returns "BackgroundMaterial"
  89502. */
  89503. BackgroundMaterial.prototype.getClassName = function () {
  89504. return "BackgroundMaterial";
  89505. };
  89506. /**
  89507. * Parse a JSON input to create back a background material.
  89508. * @param source The JSON data to parse
  89509. * @param scene The scene to create the parsed material in
  89510. * @param rootUrl The root url of the assets the material depends upon
  89511. * @returns the instantiated BackgroundMaterial.
  89512. */
  89513. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  89514. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  89515. };
  89516. /**
  89517. * Standard reflectance value at parallel view angle.
  89518. */
  89519. BackgroundMaterial.StandardReflectance0 = 0.05;
  89520. /**
  89521. * Standard reflectance value at grazing angle.
  89522. */
  89523. BackgroundMaterial.StandardReflectance90 = 0.5;
  89524. __decorate([
  89525. BABYLON.serializeAsColor3()
  89526. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  89527. __decorate([
  89528. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89529. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  89530. __decorate([
  89531. BABYLON.serialize()
  89532. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  89533. __decorate([
  89534. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89535. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  89536. __decorate([
  89537. BABYLON.serializeAsColor3()
  89538. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  89539. __decorate([
  89540. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89541. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  89542. __decorate([
  89543. BABYLON.serialize()
  89544. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  89545. __decorate([
  89546. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89547. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  89548. __decorate([
  89549. BABYLON.serializeAsColor3()
  89550. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  89551. __decorate([
  89552. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89553. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  89554. __decorate([
  89555. BABYLON.serialize()
  89556. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  89557. __decorate([
  89558. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89559. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  89560. __decorate([
  89561. BABYLON.serializeAsTexture()
  89562. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  89563. __decorate([
  89564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89565. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  89566. __decorate([
  89567. BABYLON.serialize()
  89568. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  89569. __decorate([
  89570. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89571. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  89572. __decorate([
  89573. BABYLON.serializeAsTexture()
  89574. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  89575. __decorate([
  89576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89577. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  89578. __decorate([
  89579. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89580. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  89581. __decorate([
  89582. BABYLON.serialize()
  89583. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  89584. __decorate([
  89585. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89586. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  89587. __decorate([
  89588. BABYLON.serialize()
  89589. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  89590. __decorate([
  89591. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89592. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  89593. __decorate([
  89594. BABYLON.serializeAsVector3()
  89595. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  89596. __decorate([
  89597. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89598. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  89599. __decorate([
  89600. BABYLON.serialize()
  89601. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  89602. __decorate([
  89603. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89604. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  89605. __decorate([
  89606. BABYLON.serialize()
  89607. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  89608. __decorate([
  89609. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89610. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  89611. __decorate([
  89612. BABYLON.serialize()
  89613. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  89614. __decorate([
  89615. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89616. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  89617. __decorate([
  89618. BABYLON.serialize()
  89619. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  89620. __decorate([
  89621. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89622. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  89623. __decorate([
  89624. BABYLON.serialize()
  89625. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  89626. __decorate([
  89627. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89628. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  89629. __decorate([
  89630. BABYLON.serialize()
  89631. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  89632. __decorate([
  89633. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89634. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  89635. __decorate([
  89636. BABYLON.serialize()
  89637. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  89638. __decorate([
  89639. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89640. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  89641. __decorate([
  89642. BABYLON.serialize()
  89643. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  89644. __decorate([
  89645. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89646. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  89647. __decorate([
  89648. BABYLON.serialize()
  89649. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  89650. __decorate([
  89651. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89652. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  89653. __decorate([
  89654. BABYLON.serializeAsImageProcessingConfiguration()
  89655. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  89656. return BackgroundMaterial;
  89657. }(BABYLON.PushMaterial));
  89658. BABYLON.BackgroundMaterial = BackgroundMaterial;
  89659. })(BABYLON || (BABYLON = {}));
  89660. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  89661. var __assign = (this && this.__assign) || Object.assign || function(t) {
  89662. for (var s, i = 1, n = arguments.length; i < n; i++) {
  89663. s = arguments[i];
  89664. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  89665. t[p] = s[p];
  89666. }
  89667. return t;
  89668. };
  89669. var BABYLON;
  89670. (function (BABYLON) {
  89671. /**
  89672. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  89673. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  89674. * It also helps with the default setup of your imageProcessing configuration.
  89675. */
  89676. var EnvironmentHelper = /** @class */ (function () {
  89677. /**
  89678. * constructor
  89679. * @param options
  89680. * @param scene The scene to add the material to
  89681. */
  89682. function EnvironmentHelper(options, scene) {
  89683. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  89684. this._scene = scene;
  89685. this._setupBackground();
  89686. this._setupImageProcessing();
  89687. }
  89688. /**
  89689. * Creates the default options for the helper.
  89690. */
  89691. EnvironmentHelper._getDefaultOptions = function () {
  89692. return {
  89693. createGround: true,
  89694. groundSize: 15,
  89695. groundTexture: this._groundTextureCDNUrl,
  89696. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  89697. groundOpacity: 0.9,
  89698. enableGroundShadow: true,
  89699. groundShadowLevel: 0.5,
  89700. enableGroundMirror: false,
  89701. groundMirrorSizeRatio: 0.3,
  89702. groundMirrorBlurKernel: 64,
  89703. groundMirrorAmount: 1,
  89704. groundMirrorFresnelWeight: 1,
  89705. groundMirrorFallOffDistance: 0,
  89706. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  89707. groundYBias: 0.00001,
  89708. createSkybox: true,
  89709. skyboxSize: 20,
  89710. skyboxTexture: this._skyboxTextureCDNUrl,
  89711. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  89712. backgroundYRotation: 0,
  89713. sizeAuto: true,
  89714. rootPosition: BABYLON.Vector3.Zero(),
  89715. setupImageProcessing: true,
  89716. environmentTexture: this._environmentTextureCDNUrl,
  89717. cameraExposure: 0.8,
  89718. cameraContrast: 1.2,
  89719. toneMappingEnabled: true,
  89720. };
  89721. };
  89722. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  89723. /**
  89724. * Gets the root mesh created by the helper.
  89725. */
  89726. get: function () {
  89727. return this._rootMesh;
  89728. },
  89729. enumerable: true,
  89730. configurable: true
  89731. });
  89732. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  89733. /**
  89734. * Gets the skybox created by the helper.
  89735. */
  89736. get: function () {
  89737. return this._skybox;
  89738. },
  89739. enumerable: true,
  89740. configurable: true
  89741. });
  89742. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  89743. /**
  89744. * Gets the skybox texture created by the helper.
  89745. */
  89746. get: function () {
  89747. return this._skyboxTexture;
  89748. },
  89749. enumerable: true,
  89750. configurable: true
  89751. });
  89752. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  89753. /**
  89754. * Gets the skybox material created by the helper.
  89755. */
  89756. get: function () {
  89757. return this._skyboxMaterial;
  89758. },
  89759. enumerable: true,
  89760. configurable: true
  89761. });
  89762. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  89763. /**
  89764. * Gets the ground mesh created by the helper.
  89765. */
  89766. get: function () {
  89767. return this._ground;
  89768. },
  89769. enumerable: true,
  89770. configurable: true
  89771. });
  89772. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  89773. /**
  89774. * Gets the ground texture created by the helper.
  89775. */
  89776. get: function () {
  89777. return this._groundTexture;
  89778. },
  89779. enumerable: true,
  89780. configurable: true
  89781. });
  89782. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  89783. /**
  89784. * Gets the ground mirror created by the helper.
  89785. */
  89786. get: function () {
  89787. return this._groundMirror;
  89788. },
  89789. enumerable: true,
  89790. configurable: true
  89791. });
  89792. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  89793. /**
  89794. * Gets the ground mirror render list to helps pushing the meshes
  89795. * you wish in the ground reflection.
  89796. */
  89797. get: function () {
  89798. if (this._groundMirror) {
  89799. return this._groundMirror.renderList;
  89800. }
  89801. return null;
  89802. },
  89803. enumerable: true,
  89804. configurable: true
  89805. });
  89806. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  89807. /**
  89808. * Gets the ground material created by the helper.
  89809. */
  89810. get: function () {
  89811. return this._groundMaterial;
  89812. },
  89813. enumerable: true,
  89814. configurable: true
  89815. });
  89816. /**
  89817. * Updates the background according to the new options
  89818. * @param options
  89819. */
  89820. EnvironmentHelper.prototype.updateOptions = function (options) {
  89821. var newOptions = __assign({}, this._options, options);
  89822. if (this._ground && !newOptions.createGround) {
  89823. this._ground.dispose();
  89824. this._ground = null;
  89825. }
  89826. if (this._groundMaterial && !newOptions.createGround) {
  89827. this._groundMaterial.dispose();
  89828. this._groundMaterial = null;
  89829. }
  89830. if (this._groundTexture) {
  89831. if (this._options.groundTexture != newOptions.groundTexture) {
  89832. this._groundTexture.dispose();
  89833. this._groundTexture = null;
  89834. }
  89835. }
  89836. if (this._skybox && !newOptions.createSkybox) {
  89837. this._skybox.dispose();
  89838. this._skybox = null;
  89839. }
  89840. if (this._skyboxMaterial && !newOptions.createSkybox) {
  89841. this._skyboxMaterial.dispose();
  89842. this._skyboxMaterial = null;
  89843. }
  89844. if (this._skyboxTexture) {
  89845. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  89846. this._skyboxTexture.dispose();
  89847. this._skyboxTexture = null;
  89848. }
  89849. }
  89850. if (this._groundMirror && !newOptions.enableGroundMirror) {
  89851. this._groundMirror.dispose();
  89852. this._groundMirror = null;
  89853. }
  89854. if (this._scene.environmentTexture) {
  89855. if (this._options.environmentTexture != newOptions.environmentTexture) {
  89856. this._scene.environmentTexture.dispose();
  89857. }
  89858. }
  89859. this._options = newOptions;
  89860. this._setupBackground();
  89861. this._setupImageProcessing();
  89862. };
  89863. /**
  89864. * Sets the primary color of all the available elements.
  89865. * @param color
  89866. */
  89867. EnvironmentHelper.prototype.setMainColor = function (color) {
  89868. if (this.groundMaterial) {
  89869. this.groundMaterial.primaryColor = color;
  89870. }
  89871. if (this.skyboxMaterial) {
  89872. this.skyboxMaterial.primaryColor = color;
  89873. }
  89874. if (this.groundMirror) {
  89875. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  89876. }
  89877. };
  89878. /**
  89879. * Setup the image processing according to the specified options.
  89880. */
  89881. EnvironmentHelper.prototype._setupImageProcessing = function () {
  89882. if (this._options.setupImageProcessing) {
  89883. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  89884. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  89885. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  89886. this._setupEnvironmentTexture();
  89887. }
  89888. };
  89889. /**
  89890. * Setup the environment texture according to the specified options.
  89891. */
  89892. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  89893. if (this._scene.environmentTexture) {
  89894. return;
  89895. }
  89896. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  89897. this._scene.environmentTexture = this._options.environmentTexture;
  89898. return;
  89899. }
  89900. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  89901. this._scene.environmentTexture = environmentTexture;
  89902. };
  89903. /**
  89904. * Setup the background according to the specified options.
  89905. */
  89906. EnvironmentHelper.prototype._setupBackground = function () {
  89907. if (!this._rootMesh) {
  89908. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  89909. }
  89910. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  89911. var sceneSize = this._getSceneSize();
  89912. if (this._options.createGround) {
  89913. this._setupGround(sceneSize);
  89914. this._setupGroundMaterial();
  89915. this._setupGroundDiffuseTexture();
  89916. if (this._options.enableGroundMirror) {
  89917. this._setupGroundMirrorTexture(sceneSize);
  89918. }
  89919. this._setupMirrorInGroundMaterial();
  89920. }
  89921. if (this._options.createSkybox) {
  89922. this._setupSkybox(sceneSize);
  89923. this._setupSkyboxMaterial();
  89924. this._setupSkyboxReflectionTexture();
  89925. }
  89926. this._rootMesh.position.x = sceneSize.rootPosition.x;
  89927. this._rootMesh.position.z = sceneSize.rootPosition.z;
  89928. this._rootMesh.position.y = sceneSize.rootPosition.y;
  89929. };
  89930. /**
  89931. * Get the scene sizes according to the setup.
  89932. */
  89933. EnvironmentHelper.prototype._getSceneSize = function () {
  89934. var _this = this;
  89935. var groundSize = this._options.groundSize;
  89936. var skyboxSize = this._options.skyboxSize;
  89937. var rootPosition = this._options.rootPosition;
  89938. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  89939. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  89940. }
  89941. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  89942. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  89943. });
  89944. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  89945. if (this._options.sizeAuto) {
  89946. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  89947. this._scene.activeCamera.upperRadiusLimit) {
  89948. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  89949. skyboxSize = groundSize;
  89950. }
  89951. var sceneDiagonalLenght = sceneDiagonal.length();
  89952. if (sceneDiagonalLenght > groundSize) {
  89953. groundSize = sceneDiagonalLenght * 2;
  89954. skyboxSize = groundSize;
  89955. }
  89956. // 10 % bigger.
  89957. groundSize *= 1.1;
  89958. skyboxSize *= 1.5;
  89959. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  89960. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  89961. }
  89962. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  89963. };
  89964. /**
  89965. * Setup the ground according to the specified options.
  89966. */
  89967. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  89968. var _this = this;
  89969. if (!this._ground) {
  89970. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  89971. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  89972. this._ground.parent = this._rootMesh;
  89973. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  89974. }
  89975. this._ground.receiveShadows = this._options.enableGroundShadow;
  89976. };
  89977. /**
  89978. * Setup the ground material according to the specified options.
  89979. */
  89980. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  89981. if (!this._groundMaterial) {
  89982. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  89983. }
  89984. this._groundMaterial.alpha = this._options.groundOpacity;
  89985. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  89986. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  89987. this._groundMaterial.primaryLevel = 1;
  89988. this._groundMaterial.primaryColor = this._options.groundColor;
  89989. this._groundMaterial.secondaryLevel = 0;
  89990. this._groundMaterial.tertiaryLevel = 0;
  89991. this._groundMaterial.useRGBColor = false;
  89992. this._groundMaterial.enableNoise = true;
  89993. if (this._ground) {
  89994. this._ground.material = this._groundMaterial;
  89995. }
  89996. };
  89997. /**
  89998. * Setup the ground diffuse texture according to the specified options.
  89999. */
  90000. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  90001. if (!this._groundMaterial) {
  90002. return;
  90003. }
  90004. if (this._groundTexture) {
  90005. return;
  90006. }
  90007. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  90008. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  90009. return;
  90010. }
  90011. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  90012. diffuseTexture.gammaSpace = false;
  90013. diffuseTexture.hasAlpha = true;
  90014. this._groundMaterial.diffuseTexture = diffuseTexture;
  90015. };
  90016. /**
  90017. * Setup the ground mirror texture according to the specified options.
  90018. */
  90019. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  90020. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90021. if (!this._groundMirror) {
  90022. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  90023. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  90024. this._groundMirror.anisotropicFilteringLevel = 1;
  90025. this._groundMirror.wrapU = wrapping;
  90026. this._groundMirror.wrapV = wrapping;
  90027. this._groundMirror.gammaSpace = false;
  90028. if (this._groundMirror.renderList) {
  90029. for (var i = 0; i < this._scene.meshes.length; i++) {
  90030. var mesh = this._scene.meshes[i];
  90031. if (mesh !== this._ground &&
  90032. mesh !== this._skybox &&
  90033. mesh !== this._rootMesh) {
  90034. this._groundMirror.renderList.push(mesh);
  90035. }
  90036. }
  90037. }
  90038. }
  90039. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  90040. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  90041. };
  90042. /**
  90043. * Setup the ground to receive the mirror texture.
  90044. */
  90045. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  90046. if (this._groundMaterial) {
  90047. this._groundMaterial.reflectionTexture = this._groundMirror;
  90048. this._groundMaterial.reflectionFresnel = true;
  90049. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  90050. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  90051. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  90052. }
  90053. };
  90054. /**
  90055. * Setup the skybox according to the specified options.
  90056. */
  90057. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  90058. var _this = this;
  90059. if (!this._skybox) {
  90060. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  90061. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  90062. }
  90063. this._skybox.parent = this._rootMesh;
  90064. };
  90065. /**
  90066. * Setup the skybox material according to the specified options.
  90067. */
  90068. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  90069. if (!this._skybox) {
  90070. return;
  90071. }
  90072. if (!this._skyboxMaterial) {
  90073. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  90074. }
  90075. this._skyboxMaterial.useRGBColor = false;
  90076. this._skyboxMaterial.primaryLevel = 1;
  90077. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  90078. this._skyboxMaterial.secondaryLevel = 0;
  90079. this._skyboxMaterial.tertiaryLevel = 0;
  90080. this._skyboxMaterial.enableNoise = true;
  90081. this._skybox.material = this._skyboxMaterial;
  90082. };
  90083. /**
  90084. * Setup the skybox reflection texture according to the specified options.
  90085. */
  90086. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  90087. if (!this._skyboxMaterial) {
  90088. return;
  90089. }
  90090. if (this._skyboxTexture) {
  90091. return;
  90092. }
  90093. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  90094. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  90095. return;
  90096. }
  90097. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  90098. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  90099. this._skyboxTexture.gammaSpace = false;
  90100. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  90101. };
  90102. /**
  90103. * Dispose all the elements created by the Helper.
  90104. */
  90105. EnvironmentHelper.prototype.dispose = function () {
  90106. if (this._groundMaterial) {
  90107. this._groundMaterial.dispose(true, true);
  90108. }
  90109. if (this._skyboxMaterial) {
  90110. this._skyboxMaterial.dispose(true, true);
  90111. }
  90112. this._rootMesh.dispose(false);
  90113. };
  90114. /**
  90115. * Default ground texture URL.
  90116. */
  90117. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  90118. /**
  90119. * Default skybox texture URL.
  90120. */
  90121. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  90122. /**
  90123. * Default environment texture URL.
  90124. */
  90125. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  90126. return EnvironmentHelper;
  90127. }());
  90128. BABYLON.EnvironmentHelper = EnvironmentHelper;
  90129. })(BABYLON || (BABYLON = {}));
  90130. //# sourceMappingURL=babylon.environmentHelper.js.map
  90131. var BABYLON;
  90132. (function (BABYLON) {
  90133. /**
  90134. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  90135. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  90136. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  90137. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  90138. */
  90139. var VideoDome = /** @class */ (function (_super) {
  90140. __extends(VideoDome, _super);
  90141. /**
  90142. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  90143. * @param name Element's name, child elements will append suffixes for their own names.
  90144. * @param urlsOrVideo
  90145. * @param options An object containing optional or exposed sub element properties:
  90146. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  90147. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  90148. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  90149. * @param options **loop=true** Automatically loop video on end.
  90150. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  90151. */
  90152. function VideoDome(name, urlsOrVideo, options, scene) {
  90153. var _this = _super.call(this, name, scene) || this;
  90154. // set defaults and manage values
  90155. name = name || "videoDome";
  90156. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  90157. options.clickToPlay = Boolean(options.clickToPlay);
  90158. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  90159. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  90160. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  90161. // create
  90162. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  90163. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  90164. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  90165. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  90166. flat: false,
  90167. radius: options.size,
  90168. subdivisions: options.resolution,
  90169. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  90170. }, scene);
  90171. // configure material
  90172. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  90173. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  90174. material.reflectionTexture = _this._videoTexture;
  90175. material.useEquirectangularFOV = true;
  90176. material.fovMultiplier = 1.0;
  90177. // configure mesh
  90178. _this._mesh.material = material;
  90179. _this._mesh.parent = _this;
  90180. // optional configuration
  90181. if (options.clickToPlay) {
  90182. scene.onPointerUp = function () {
  90183. _this._videoTexture.video.play();
  90184. };
  90185. }
  90186. return _this;
  90187. }
  90188. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  90189. /**
  90190. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  90191. * Also see the options.resolution property.
  90192. */
  90193. get: function () {
  90194. return this._material.fovMultiplier;
  90195. },
  90196. set: function (value) {
  90197. this._material.fovMultiplier = value;
  90198. },
  90199. enumerable: true,
  90200. configurable: true
  90201. });
  90202. /**
  90203. * Releases all associated resources
  90204. */
  90205. VideoDome.prototype.dispose = function () {
  90206. _super.prototype.dispose.call(this);
  90207. this._videoTexture.dispose();
  90208. this._mesh.dispose();
  90209. this._material.dispose();
  90210. };
  90211. return VideoDome;
  90212. }(BABYLON.Node));
  90213. BABYLON.VideoDome = VideoDome;
  90214. })(BABYLON || (BABYLON = {}));
  90215. //# sourceMappingURL=babylon.videoDome.js.map
  90216. 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\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<0.4)\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)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\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*vRefractionInfos.x;\n#endif\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*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\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*vReflectionInfos.x;\n#endif\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\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)\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#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\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\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(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).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(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).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=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*=vReflectionInfos.x;\nenvironmentRadiance*=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=toLinearSpace(texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb)*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(reflectionCoords,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*=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\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\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;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef 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\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\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\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}","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 vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*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); \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}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\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\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+vec4(offset*size,0,1.0));\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 vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float angle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,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) {\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*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(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h/height;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (angle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-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;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+(direction+gravity)*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\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}","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#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 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{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\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 vec2 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.y*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;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\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);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/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;\n}\ngl_FragColor=original;\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);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\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}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,coc,1.0);\n}\n","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D originalSampler;\nuniform sampler2D circleOfConfusionSampler;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n\nvarying vec2 vUV;\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(originalSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred1=texture2D(textureSampler,vUV);\ngl_FragColor=mix(original,blurred1,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(textureSampler,vUV); \nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred2,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nvec4 blurred3=texture2D(textureSampler,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred1,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred1,blurred2,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred2,blurred3,(coc-0.66)/0.34);\n}\n#endif\n}\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}","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}\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{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\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\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\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\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{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,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\nvec3 reflectionColor=vec3(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).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=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*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\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,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,color.rgb);\n#endif\ngl_FragColor=color;\n}\n"};
  90217. 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}\nvec3 dither(vec2 seed,vec3 color) {\nfloat rand=getRand(seed);\ncolor+=mix(-0.5/255.0,0.5/255.0,rand);\ncolor=max(color,0.0);\nreturn color;\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};\nuniform sampler2D shadowSampler{X};\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;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\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};\nuniform sampler2D shadowSampler{X};\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 computeShadowWithPCFCube(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 computeShadowWithPCF(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#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=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\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=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\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,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,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,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#else\n#ifdef 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#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,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#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)\n{\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 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\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,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);\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,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);\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,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);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\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\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\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 vSecondaryColor;\nuniform vec4 vTertiaryColor;\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};"};
  90218. (function universalModuleDefinition(root, factory) {
  90219. var f = factory();
  90220. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  90221. globalObject["BABYLON"] = f;
  90222. if(typeof exports === 'object' && typeof module === 'object')
  90223. module.exports = f;
  90224. else if(typeof define === 'function' && define.amd)
  90225. define("BABYLON", factory);
  90226. else if(typeof exports === 'object')
  90227. exports["BABYLON"] = f;
  90228. else {
  90229. root["BABYLON"] = f;
  90230. }
  90231. })(this, function() {
  90232. return BABYLON;
  90233. });